静态constexpr模板数组成员本身递归所需

Jon*_*nas 7 templates constexpr c++11

我想要一个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;
}
Run Code Online (Sandbox Code Playgroud)

当然,实际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.
Run Code Online (Sandbox Code Playgroud)

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

Cal*_*eth -2

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

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