How to fix a binding error when using a template class with static constexpr?

I have the following code

#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;
}

The compilation goes fine, but I have a communication error that I don’t understand

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
+4
source share
1 answer

You cannot just define it for one type, you need

template<class T> constexpr int A<T>::arr[5];
+7
source

All Articles