“递归嵌套模板”的实际使用示例是什么?

时间:2018-07-02 09:45:07

标签: c++ recursion template-meta-programming

我发现this question中提到的这种特殊模式。

这种模板的实际用途是什么?

#include <iostream>
using namespace std;

template<typename T>
struct Recursive
{
    using cycle = struct X : Recursive<X> { int a; };
    cycle c;
};

int main() 
{
    Recursive<int> x;
    // cout<< x.c.a; // this gives infinite recursion error
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您编写的代码的一种用途是通过在编译时读取错误消息来了解编译器的模板深度是什么:

使用clang

<source>:8:11: fatal error: recursive template instantiation exceeded maximum depth of 1024

使用gcc

<source>:7:26: fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum)

 using cycle = struct X : Recursive<X> { int a; };
相关问题