递归定义的嵌套类型(就不完整类型而言)

Nik*_*iou 3 c++ templates crtp incomplete-type c++11

Break定义中的递归在哪里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;
}
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,上面的代码可以编译- 它是一段有效的代码吗?如果是,该类型的含义(简要描述)是什么cycle

Tem*_*Rex 5

struct X : Recursive<X>是奇怪重复模板模式的一个示例,但除非您访问嵌套类型,否则不会发生无限递归cycle。例如decltype(x)::cycle与 属于不同类型decltype(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;
}
Run Code Online (Sandbox Code Playgroud)

这打印

Recursive<int>

Recursive<int>::X

Recursive<Recursive<int>::X>::X

因此,递归将永远持续下去,但前提是您显式访问进一步嵌套的cycle类型。