递归定义的嵌套类型(就不完整类型而言) [英] Recursively defined nested types (in terms of incomplete types)

查看:103
本文介绍了递归定义的嵌套类型(就不完整类型而言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Where does the recursion in the definition of cycle break ?

#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;
}

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

To my surprise the above code compiles - Is it a valid piece of code and if yes what's the meaning (a brief description) of the type cycle ?

推荐答案

struct X : Recursive<X>是好奇重复模板模式的一个示例,但是除非您访问,否则不会发生无限递归.嵌套cycle类型.例如. decltype(x)::cycledecltype(x)::cycle::cycle具有不同的类型.

The struct X : Recursive<X> is an example of the Curiously Recurring Template Pattern, but there is no infinite recursion taking place unless you access the nested cycle type. E.g. decltype(x)::cycle is of a different type than 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;
}

此打印

Recursive<int>

Recursive<int>::X

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

因此,只有在您明确访问其他嵌套的cycle类型时,这种回响才会永远持续下去.

So the recusion will go on forever, but only if you explicitly access a further nested cycle type.

这篇关于递归定义的嵌套类型(就不完整类型而言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆