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

时间:2023-03-10
本文介绍了C++ 静态模板成员,每个模板类型一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

这篇关于C++ 静态模板成员,每个模板类型一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:获取元组元素类型的索引? 下一篇:g++ 不采用可变参数推导指南,clang++ 采用-谁是正确的?

相关文章