使用用户定义的文字初始化constexpr数组

时间:2012-12-04 01:08:25

标签: c++ c++11 constexpr list-initialization

简化版

class C {
 public:
 static constexpr std::array<C, 2> foo {{"1"_C, "2"_C}};
 int x;
 constexpr C(char c) { x=c; }
}
constexpr C operator"" _C(const char * str, size_t n) { return C(*str); }

这不会飞,因为在定义数组的行中不理解文字。但是免费的文字函数不能提前移动,因为那时C是不知道的。

是否有解决这个难以解决的问题,并没有涉及在代码中添加可变参数模板或类似的东西?

1 个答案:

答案 0 :(得分:3)

问题并不在于用户定义的文字,而在于std::array需要完整类型(或者实际上,任何constexpr初始化都需要)。以下代码也将无法编译:

#include <array>

class C {
public:
 static constexpr std::array<C, 2> foo {{C('1'), C('2')}};
 int x;
 constexpr C(char c) : x(c) {} // please use a mem-initializer-list
};

错误类似于(Clang 3.3 SVN):

/usr/include/c++/v1/array:136:16: error: field has incomplete type 'value_type'
      (aka 'C')
    value_type __elems_[_Size > 0 ? _Size : 1];
               ^
t.cpp:5:36: note: in instantiation of template class 'std::__1::array'
      requested here
 static constexpr std::array<C, 2> foo {{C('1'), C('2')}};
                                   ^
t.cpp:3:7: note: definition of 'C' is not complete until the closing '}'
class C {
      ^
相关问题