gpt4 book ai didi

c++ - 对静态 constexpr 的 undefined reference

转载 作者:IT老高 更新时间:2023-10-28 23:20:13 25 4
gpt4 key购买 nike

在此代码段中:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com