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

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

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 类型的含义(简要说明)是什么?

最佳答案

struct X : Recursive<X>是 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<int>

Recursive<int>::X

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

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

关于c++ - 递归定义的嵌套类型(就不完整类型而言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25009560/

相关文章:

django - 使用forloop.counter值作为Django模板中的列表索引

c++ - 迭代器中reduce和decrease的区别

c++ - 适当的 boolean 随机生成器(伯努利分布)

c++ - 使用 cin 在一行上读取多个 int

C++ std::sort 实现

c++ - 为什么类成员函数不能接受多个与其类相同类型的参数

c++ - 具有继承性的模板参数推断

c++ - std::sort() 的自定义元组比较器

c++ - SWIG 和 C++ 构造函数

c++ - std::vector 内部结构