C++ static template member, one instance for each template type?(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++ 静态模板成员,每个模板类型一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 静态模板成员,每个模板类型一个实例?
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
