3

According to this question's answer:

According to the standards you must define i (which is a static const member) outside of the class definition

... but if I do that for static const member variables of a template class which are themselves generic, then I get linking errors (similar to getting linking errors if the template code is in a separate compilation unit). If I define them in the header, the linking errors disappear (I asked whether it was OK to define them in a generic way in the first place in this question).

Is what I am doing, safe? Below is one of the definitions of a static const member variable which is in the header.

  template<typename T, unsigned int T_Size> 
  const Vector<T, T_Size> Vector<T, T_Size>::Zero = Vector<T, T_Size>(0);
Community
  • 1
  • 1
Samaursa
  • 16,527
  • 21
  • 89
  • 160
  • Can you post a complete example of failure? This problem is sensitive to the details. You should put the generic static const member initialization in the header in any case. You can also request explicit instantiation of a template in a translation unit via `template Vector;`. – Kerrek SB Jun 22 '11 at 01:46
  • @Kerrek: Just put the definition in the question in a .cpp instead of the header. – Xeo Jun 22 '11 at 01:49
  • @Xeo: Works fine for me, I can't reproduce the linker error. – Kerrek SB Jun 22 '11 at 01:53
  • @Kerrek: Included the header with the template in multiple translation units? – Xeo Jun 22 '11 at 01:54
  • @Kerrek, if I do explicit instantiation, then there are no linking errors, but since this Vector class is generic that would not be a solution. As for the error, if you put the definition in the `*.cpp` file _without_ explicit instantiation of the template and then try to instantiate one in another compilation unit, you will get the linking error. – Samaursa Jun 22 '11 at 13:55
  • @Samaursa: Right, the templated static const member initialization must be available to all consumers, so it has to be in the header. It cannot just be in one single .cpp file. – Kerrek SB Jun 22 '11 at 14:18

2 Answers2

6

Static data members of a class template have to be defined in a header file. Only when you are defining static members of an explicitly specialized template, you have to define them in an implementation file.

In other words, the rule is the same as for member functions of class templates.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2

Since a complete definition of the template is needed in every translation unit, yes, this is the way to go.

Xeo
  • 129,499
  • 52
  • 291
  • 397