Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static template class variables with different instantiations the same?

Say I have the class

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

Now what will happen in the following assignments?

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

What's going to happen according to the standard? Am I gonna have two versions of MyClass::myvar or just one?

like image 823
The Quantum Physicist Avatar asked Oct 09 '13 14:10

The Quantum Physicist


2 Answers

Yes, there will be two variables with two different values. But that's because the two are completely unrelated classes. That's how templates work. Don't think of them as classes, but rather as a set of rules after which classes are built.

like image 114
Luchian Grigore Avatar answered Nov 15 '22 06:11

Luchian Grigore


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

Each specialization will have it's own copy of myvar which makes sense since each is it's own distinct class. The C++ draft standard in section 14.7 Template instantiation and specialization paragraph 6 says(emphasis mine):

Each class template specialization instantiated 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 ]

like image 35
Shafik Yaghmour Avatar answered Nov 15 '22 05:11

Shafik Yaghmour