Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to static constexpr

Tags:

c++

c++11

In this code snippet:

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

with gcc 5.2 I got undefined reference to Foo<5ul>::arr, while clang 3.7 gives a compile time error:

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

What is wrong, and how should static constexpr be defined outside class declaration?

like image 405
user1244932 Avatar asked Oct 24 '15 20:10

user1244932


1 Answers

The out-of-line definiton is the same as for other static (non integral) members, minus the initialization:

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

Like other static members, this goes in a header - like the class template itself.

like image 154
melak47 Avatar answered Oct 08 '22 03:10

melak47