【问题标题】:What is an example practical use of 'recursively nested template'?“递归嵌套模板”的实际使用示例是什么?
【发布时间】:2018-07-02 09:45:07
【问题描述】:

我发现了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;
}

【问题讨论】:

  • 我认为对于像transform.transform.transform这样团结一致的事情......你可以永远继续下去,但除了增加冗长之外我认为没有用
  • 某事是可能的,并不意味着它有实际用途。 仅禁止这种构造 会很困难。禁止这种构造和未指定的其他东西可能会禁止有用的东西
  • 报错,没有用。
  • 我怀疑他们已经把这个作为一个容易犯的错误的例子。当您在每个递归中更改输入模板类型或值并添加一个中断递归的特化(例如在 0 或 1)时,递归模板的用处就出现了。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2016-01-03
    • 2011-03-06
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多