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

C++ static template member, one instance for each template type?(C++ 静态模板成员,每个模板类型一个实例?)
本文介绍了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++ 静态模板成员,每个模板类型一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)