Static member variable in class template

If you have a (not templated) class containing a static member, for example:

class Foo
{
   public:

   static int x;
};

Then it Foo::xmust be defined in one and only one translation unit, or the compiler will complain about several definitions. Therefore, in somefile.cppyou will need to define it:

int Foo::x = 10;

Thus, any translation unit that refers to Foo::xrefers to the same memory address.

But what if it Foois a class template?

template <class T>
class Foo
{
   public:

   static int x;
};

Now Foo<T>::xyou can define in the header file by saying:

template <class T>
int Foo<T>::x = 10;

, foo.hpp Foo, translation_unit1.cpp translation_unit2.cpp foo.hpp, Foo<T>::x Foo, ( , Foo<int>::x) ?

+4
3

, , , , , ++ 3.2 , 6, ( ):

( 9), (7.2), (7.1.2), ( 14), (14.5.6), (14.5.1.3), -

14.5.1.3 , 1, :

, .

:

template<class T> class X {
  static T s;
};
template<class T> T X<T>::s = 0;
+3

[basic.def.odr]/6 " " ( ) .

D:

D , , D. D , undefined.

, , TU, , TU.


, , :

, , , , , , - , , , . D, ,

  • D ;
  • D, , 3.4, , D, , , const , D, , ( ) , D;
  • D, ;
  • D, , , , , , , D;
  • D , ( ) , , D; , (, , ).
  • D - , , odr, D.

D , , , , , D , , D. D , undefined.

+1

Your question was answered perfectly by 14.4 in the C ++ 11 standard:

The name of the template has a link (3.5). A non-member function template may have an internal relationship; any other template name must have external binding ...

Therefore, the class template will always have an external connection, as well as its static data members (const or not). Thus, Foo<int>::xit will always refer to the same object in memory, regardless of in which units of translation this expression appears. Linker does this.

+1
source

All Articles