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?
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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With