Samaursa
Samaursa

Reputation: 17271

Where to define static const member variables of a template class

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

Upvotes: 3

Views: 2641

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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.

Upvotes: 6

Xeo
Xeo

Reputation: 131907

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

Upvotes: 2

Related Questions