C++静态模板成员,每种模板类型一个实例?
通常,一个类的静态成员/对象对于具有静态成员/对象的类的每个实例是相同的。无论如何,如果静态对象是模板类的一部分并且还依赖于模板参数怎么办?例如,像这样:
template<class T>
class A{
public:
static myObject<T> obj;
}
如果我将 A 的一个对象转换为 int,将另一个对象转换为 float,我猜会有两个 obj ,每种类型一个?
如果我创建 A 的多个对象作为 int
类型和多个 float
,它仍然是两个 obj
实例,因为我只使用两种不同的类型?
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;
}
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?
If I would create multiple objects of A as type int
and multiple float
s, would it still be two obj
instances, since I am only using two different types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个不同的模板初始化的静态成员都是不同的。这是因为每个模板初始化都是一个不同的类,由编译器第一次遇到模板的特定初始化时生成。
以下代码显示了静态成员变量不同的事实
:
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:
Which results in
A
和A
是两种完全不同的类型,您无法在它们之间安全地进行转换。不过,A
的两个实例将共享相同的静态 myObject。A<int>
andA<float>
are two entirely different types, you cannot cast between them safely. Two instances ofA<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.
在 C++ 中,模板实际上是类的副本。我认为在您的示例中,每个模板实例都有一个静态实例。
In C++ templates are actually copies of classes. I think in your example there would be one static instance per template instance.