-1

I implement an template which have static member variable, after read the standard, seams it is correct to define the variable in the .h file, but the .h file is included in multiple .cpp, so why the static variable is not multiple definition?

Any reference in standard for that?

14.5.1.3 in N3376

A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template. [Example:

template<class T> class X { static T s; };

template<class T> T X<T>::s = 0; <-------------Question here.

—end example ]

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
ZijingWu
  • 3,350
  • 3
  • 25
  • 40

1 Answers1

2

Because it's a template. When you instantiate the static member it will be defined, but implicit instantiations are allowed to be defined in multiple translation units.

[basic.def.odr]/6

There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521