Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix linkage error when using 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;
}

Compilation passes just fine but I have a linkage error which 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
like image 416
e271p314 Avatar asked Mar 23 '23 04:03

e271p314


1 Answers

You can not just define it for one type, you need

template<class T> constexpr int A<T>::arr[5];
like image 128
Daniel Frey Avatar answered Apr 06 '23 08:04

Daniel Frey