【问题标题】:Recursively defined nested types (in terms of incomplete types)递归定义的嵌套类型(就不完整类型而言)
【发布时间】:2023-03-31 04:19:01
【问题描述】:

cycle定义中的递归在哪里中断?

#include <iostream>
using namespace std;

template<typename T>
struct Recursive
{
    using cycle = struct X : Recursive<X> {}; // would work for Recursive<T> as well
};

int main() 
{
    Recursive<int> x;
    return 0;
}

令我惊讶的是上面的代码compiles - 它是一段有效的代码吗?如果是,cycle 类型的含义(简要说明)是什么?

【问题讨论】:

    标签: c++ templates c++11 crtp incomplete-type


    【解决方案1】:

    struct X : Recursive&lt;X&gt; 是 Curiously Recurring Template Pattern 的一个示例,但除非您访问嵌套的 cycle 类型,否则不会发生无限递归。例如。 decltype(x)::cycledecltype(x)::cycle::cycle 的类型不同。

    #include <iostream>
    #include <type_traits>
    #include <typeinfo>
    #include <cxxabi.h>
    
    using namespace std;
    
    template<typename T>
    struct Recursive
    {
        using cycle = struct X : Recursive<X> {};
    };
    
    
    int main() 
    {
        int status;
        Recursive<int> x;
        std::cout << abi::__cxa_demangle(typeid(x).name(), 0, 0, &status) << '\n';
        std::cout << abi::__cxa_demangle(typeid(decltype(x)::cycle).name(), 0, 0, &status) << '\n';
        std::cout << abi::__cxa_demangle(typeid(decltype(x)::cycle::cycle).name(), 0, 0, &status) << '\n';
        return 0;
    }
    

    打印出来

    Recursive&lt;int&gt;

    Recursive&lt;int&gt;::X

    Recursive&lt;Recursive&lt;int&gt;::X&gt;::X

    因此,recusion 将永远持续下去,但前提是您明确访问进一步嵌套的 cycle 类型。

    【讨论】:

    • 我的问题不是关于 CRTP,而是关于如何允许嵌套类型(以循环方式)取决于封闭类。例如在节点类型的链接列表中看到的东西很常见(尽管是指针),但在帖子中的使用对我来说是新的。我们是在谈论不完整类型和从不完整类型派生(肯定Recursive 在派生时尚未定义X 然后cycle)还是在我们谈论派生时适用其他规则?
    • @NikosAthanasiou 更新:X : Recursive&lt;X&gt; 是 CRTP。那里既没有无限递归也没有任何其他错误。你可以在调用代码中递归访问cycle,并为每个级别获取一个新类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2019-05-07
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多