使用带有静态constexpr的模板类时如何修复链接错误?

e27*_*314 4 c++ constexpr c++11

我有以下代码

#include <iostream>
template <class T>
class A
{
public:
    static constexpr int arr[5] = {1,2,3,4,5};
};

template<> constexpr int A<int>::arr[5];

int main()
{
    A<int> a;
    std::cout << a.arr[0] << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译通过很好,但我有一个链接错误,我不明白

g++ -std=c++11 test.cpp -o test
/tmp/ccFL19bt.o: In function `main':
test01.cpp:(.text+0xa): undefined reference to `A<int>::arr'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

Dan*_*rey 7

您不能只为一种类型定义它

template<class T> constexpr int A<T>::arr[5];
Run Code Online (Sandbox Code Playgroud)