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

十年热恋 提交于 2019-11-27 05:06:06

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

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.

There are as many static member variables as there are classes and this applies equally to templates. Each separate instantiation of a template class creates only one static member variable. The number of objects of those templated classes is irrelevant.

In C++ templates are actually copies of classes. I think in your example there would be one static instance per template instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!