6

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?

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189
  • 1
    @ShafikYaghmour I'm writing a manual for a huge set of classes, and this question occured to me, because I have a static function that sets some static variables, and I thought it could be a good question for the public. Probably knowing what the standard says about it is better than trying. – The Quantum Physicist Oct 09 '13 at 14:30
  • 1
    @TheQuantumPhysicist Ok, that makes sense, I found the quote from the standard which says that each specialization will have a copy of any static members. – Shafik Yaghmour Oct 09 '13 at 14:38

3 Answers3

7

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    STL once said (paraphrasing): "templates are cookie cutters. You can't eat cookie cutters but you can make cookies that you *can* eat with a cookie cutter". :P – Simple Oct 09 '13 at 14:45
2

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 ]

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

A completely 'new class' is instantiated from the template for 'each typename'. And since static member are tied to class, each of these classes have their own copies of the static variable.

theAlias
  • 396
  • 1
  • 14