Are the static variables of the template class with different instances the same?

Say I have a class

template <typename T> class MyClass { static int myvar; } 

Now, what will happen in the following appointments?

 MyClass<int>::myvar = 5; MyClass<double>::myvar = 6; 

What will happen according to the standard? Can I have two versions of MyClass :: myvar or only one?

+6
source share
3 answers

Since the OP specifically requested a quote from the standard, here is my answer, which includes the corresponding quote from the standard.

Each specialization will have its own copy of myvar , which makes sense, since each of them is its own class. The draft C ++ standard in section 14.7 The description of the template instance and specialization in paragraph 6 says (emphasis added):

Each specialized class template specification created from a template has its own copy of any static members .

  [ Example: template<class T> class X { static T s; }; template<class T> T X<T>::s = 0; X<int> aa; X<char*> bb; 

X has a static member s of type int, and X has a static member s of type char *. -end example]

+2
source

Yes, there will be two variables with two different values. But this is because the two are completely unrelated classes . This is how templates work. Do not consider them as classes, but rather as a set of rules after which classes are created.

+7
source

A completely "new class" is created from the template for "each typename". And since the static member is bound to a class, each of these classes has its own copies of the static variable.

+1
source

Source: https://habr.com/ru/post/955583/


All Articles