C++ static template member, one instance for each template type?

Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template.

The fact that static member variables are different is shown by this code:

#include <iostream>

template <class T> class Foo {
  public:
    static int bar;
};

template <class T>
int Foo<T>::bar;

int main(int argc, char* argv[]) {
  Foo<int>::bar = 1;
  Foo<char>::bar = 2;

  std::cout << Foo<int>::bar  << "," << Foo<char>::bar;
}

Which results in

1,2

Leave a Comment