12

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But where this should go? if it is in header file, will I got multiply definition if include into several files? If it is in c++ file, then how compiler handle different specilizations?
Put it in the header. Since it is a template definition, it has to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.