C++ 静态模板成员,每个模板类型一个实例?

2021-12-13 00:00:00 static templates c++ member

通常一个类的静态成员/对象对于具有静态成员/对象的类的每个实例都是相同的.无论如何,如果静态对象是模板类的一部分并且还依赖于模板参数呢?例如,像这样:

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;
}

如果我将 A 的一个对象转换为 int 并将另一个对象转换为 float,我想会有两个 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?

如果我创建多个类型为 int 和多个 float 的 A 对象,它是否仍然是两个 obj 实例,因为我我只使用两种不同的类型?

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?

推荐答案

静态成员对于每个不同的模板初始化都是不同的.这是因为每个模板初始化都是由编译器在第一次遇到模板的特定初始化时生成的不同类.

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;
}

结果

1,2

相关文章