1

I have a static array inside a class template. The linker complains about a undefined symbol and even after applying the tips I saw on the web, I can't figure out what goes wrong.

Header

template<unsigned int N1, unsigned int N2>
class Foo 
{
private:
    static const int Size = N1 * N2;

public:
// stuff

private:
    static float mArray[Size];

}

CPP

template <unsigned int N1, unsigned int N2>
float Foo<N1, N2>::mArray[size] = {0};

The linker complains about Foo<...>::mArray not being defined. I got it to compile (and link) when I move the definition to the header but I know that this is bad practice for statics. What is the best approach here?

Cheers

ruhig brauner
  • 943
  • 1
  • 13
  • 35
  • @πάνταῥεῖ I wouldn't be so sure about the duplicate - none of the answers there actually mentions static data members, and it's not immediately obvious the rule applies to them as well. Especially as normally you would get a linker erro from putting a static data member definition in a header file. – Angew is no longer proud of SO Oct 28 '15 at 12:21
  • 1
    @Angew Well, `static` class members of a template class aren't anyhow special regarding the rules and solutions mentioned in the dupe. – πάντα ῥεῖ Oct 28 '15 at 12:24

1 Answers1

5

As with nearly everything else template-y, the definition of the static data member of a class template needs to be accessible in all translation units using it—in other words, put it in the header file. The compiler+linker are required to make this work without multiple-definition errors.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455