c++ - 对静态 constexpr 的 undefined reference

标签 c++ c++11

在此代码段中:

template <size_t N>
struct Foo {
   static constexpr std::array<char, N> arr{{0}};
   static const char *data() { return &arr[0]; }
};

template<>
constexpr std::array<char, 5> Foo<5>::arr;

int main()
{
   std::cout << Foo<5>::data() << std::endl;
}

使用 gcc 5.2 我得到了对 Foo<5ul>::arr 的 undefined reference ,而 clang 3.7 给出了编译时错误:

declaration of constexpr static data member 'arr' requires an initializer

出了什么问题,怎么办static constexpr在类声明之外定义?

最佳答案

行外定义与其他静态(非整型)成员相同,但不包括初始化:

template<size_t N>
constexpr std::array<char, N> Foo<N>::arr;

与其他静态成员一样,它位于标题中 - 就像类模板本身一样。

关于c++ - 对静态 constexpr 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33322819/

相关文章:

c++ - 了解可变参数模板函数中的点

c++ - 将 uint8_t 的 vector 转换为位集

c++ - C++17 中的新功能 : template templates that match by default

c++ - 使用 C++ 容器最小化内存开销(std::map 和 std::vector 太贵了)

c++ - 将带有参数的回调函数传递给函数

c++ - 使用构造函数向 std::set 插入一个元素

c++ - 有没有办法将指针转换为数组类型?

c++11 - 引用折叠规则是否适用于返回类型?

c++ - 无法找到并替换 vector 的所有出现

c++ - 使用数组 C++ 的动态堆栈