【问题标题】:static constexpr template array member recursively required by itself自身递归需要的静态 constexpr 模板数组成员
【发布时间】:2017-09-02 21:59:53
【问题描述】:

我想要一个类似于以下代码的模板类中的 static constexpr 类元素数组:

struct Element {
    unsigned i;
    constexpr Element (unsigned i) : i(i) { }
};

template <bool Reverse>
struct Template {
     static constexpr Element element[] = {
         Element (Reverse ? 1 : 0),
         Element (Reverse ? 0 : 1),
     };
};

int main (int argc, char **argv) {
    return Template<true>::element[0].i;
}

当然,实际的Element 结构比这个例子中的复杂,但它已经说明了问题。如果我编译这个机智gcc 我得到一个关于递归依赖的错误:

test.cc: In instantiation of ‘constexpr Element Template<true>::element [2]’:
test.cc:11:27:   recursively required from ‘constexpr Element Template<true>::element [2]’
test.cc:11:27:   required from ‘constexpr Element Template<true>::element [2]’
test.cc:20:2:   required from here
test.cc:11:27: fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum)
  static constexpr Element element[] = {
                       ^
compilation terminated.

首先我很好奇如何规避这个错误,但如果我能得到这个原因的提示或者为什么这样的构造不应该是有效的......

【问题讨论】:

  • 你有什么版本的 GCC?我无法用任何编译器重现。
  • 我已经测试了g++-5.4.0。我刚刚注意到,如果我只使用上面的摘录,编译器不会失败。之后我必须使用Template&lt;bool&gt;::element..
  • 似乎是编译器的错误。作为一种解决方法,it worksstd::array
  • 现在我可以复制它试试....rextester.com/YDN72048
  • @Jonas,真正的代码是使用 作为模板吗?也许只是专攻它?

标签: c++11 templates constexpr


【解决方案1】:

您需要指定 Element 数组的大小。 Element element[] 不是有效的 C++。

template <bool Reverse>
struct Template {
     static constexpr Element element[2] = {
         Element (Reverse ? 1 : 0),
         Element (Reverse ? 0 : 1),
     };
};

【讨论】:

猜你喜欢
  • 2017-01-15
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多