Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a template class and also depends on the template argument? For example, like this:

template<class T>
class A{
public:
  static myObject<T> obj;
}

If I would cast one object of A as int and another one as float, I guess there would be two obj, one for each type?

If I would create multiple objects of A as type int and multiple floats, would it still be two obj instances, since I am only using two different types?

like image 889
user240137 Avatar asked Feb 08 '10 10:02

user240137


2 Answers

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
like image 90
Yacoby Avatar answered Nov 10 '22 13:11

Yacoby


A<int> and A<float> are two entirely different types, you cannot cast between them safely. Two instances of A<int> will share the same static myObject though.

like image 38
villintehaspam Avatar answered Nov 10 '22 12:11

villintehaspam