为什么模板类的静态成员不是唯一的 [英] Why are static members of template classes not unique
问题描述
请看下面的代码:
#include <iostream>
template <typename T>
class Foo
{
public:
static T bar;
};
template <typename T> typename T Foo<T>::bar;
int main() {
std::cout << "Foo<int>::bar : " << &Foo<int>::bar << std::endl;
std::cout << "Foo<double>::bar : " << &Foo<double>::bar << std::endl;
return 0;
}
这将打印出2个不同的地址。我可以理解为什么在这种情况下, bar
是类型 T
,因此在<$ c $中实例化不同的T c> Foo< T> 将获得不同的静态成员。但是,如果我们将 bar
更改为我们已经知道的类型(例如 static int bar
),则会发生。
This will print out 2 different addresses. I can understand why in this case, bar
is of type T
and thus instantiations of different T's in Foo<T>
will get you different static members. However, if we change bar
to a type we already know ( e.g. static int bar
) this still happens.
为什么会这样?为什么不为多个模板实例重复使用 bar
?
Why is this the case? Why just not re-use bar
for multiple template instantiations? How would I be able to get just 1 bar
object throughout different instantiations?
推荐答案
如何在不同的实例中获得只有1 bar
这里没有什么真正令人惊讶的。
There is nothing really surprising going on here.
template <typename T>
class Foo
{
//...
};
不是一个类,它是一个模板来打印类。这意味着 Foo< A>
是与 Foo
完全不同的类。因此,所有静态成员对于不同实例化类是唯一的。和类模板相同的事实在这个上下文没有相关性,因为它是所有的模板,实例化的类的蓝图。
Is not a class, it is a template to stamp out classes. That means Foo<A>
is a completely different class from Foo<B>
. As such all static members are unique to the different instantiated classes — and the fact that class template being same has no relevance in this context, as it is after all a template, the blueprint of the instantiated classes.
如果你想要所有不同种类的 Foo
的共享一个共同的状态,那么你可以让他们继承相同的基类,并把公共信息。这是一个非常沸腾的例子:
If you want all the different kinds of Foo
's to share a common state then you can have them inherit from the same base class and put the common information there. Here is a very boiled down example:
struct Foo_Base
{
static int bar;
};
int Foo_Base::bar = 10;
template<typename T>
struct Foo : Foo_Base {};
int main()
{
Foo<int> foo_i;
Foo<double> foo_d;
std::cout << foo_i.bar << "\n";
foo_i.bar += 10;
std::cout << foo_d.bar;
}
输出:
10
20
这篇关于为什么模板类的静态成员不是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!