初始化模板化类的静态成员 [英] Initializing static members of a templated class
问题描述
我试图弄清楚为什么这个例子不能编译.我的理解是,如果未显式设置静态变量,则其默认值为0.在下面的五个示例中,其中四个示例的行为与我期望的一样,但是被注释掉的示例将无法编译.
I'm trying to figure out why this example doesn't compile. My understanding is that if a static variable is not explicitly set then it defaults to 0. In the five examples below four of them behave as I would expect, but the one that's commented out won't compile.
#include <iostream>
class Foo
{
public:
static int i;
static int j;
};
template <int n>
class Bar
{
public:
Bar(int) { }
static int i;
};
static int i;
int Foo::i;
int Foo::j = 1;
template <> int Bar<2>::i;
template <> int Bar<3>::i = 3;
int main(int argc, char** argv)
{
std::cout << "i " << i << std::endl;
std::cout << "Foo::i " << Foo::i << std::endl;
std::cout << "Foo::j " << Foo::j << std::endl;
//std::cout << "Bar<2>::i " << Bar<2>::i << std::endl; // Doesn't compile?
std::cout << "Bar<3>::i " << Bar<3>::i << std::endl;
return 0;
}
int Bar<2>::i
为什么不做与int Foo::i
或static int i
相同的事情?
Why doesn't int Bar<2>::i
do the same thing as int Foo::i
or static int i
?
我忘记将模板<>添加到Bar< 2>和Bar< 3>声明中. (虽然不能解决问题,但仍然会出现链接器错误)
I had forgotten to add template<> to the Bar<2> and Bar<3> declarations. (doesn't solve the problem though, still getting linker errors)
推荐答案
在当前C ++标准的规则下,特化template <> int Bar<2>::i;
只是声明,而不是定义.
要成为定义,必须指定一个初始化程序. (请参阅第14.7.3/15条)
Under the rules of the current C++ standard, the specialisation template <> int Bar<2>::i;
is only a declaration and never a definition.
To become a definition, you must specify an initialiser. (See clause 14.7.3/15)
除此之外,您还缺少一种非常常见的情况:模板的非专业静态成员的定义:
Apart from that, you were missing one very common case: the definition of a non-specialised static member of a template:
template <int n> int Bar<n>::i;
这为N不等于2或3的Bar<N>::i
提供了定义.
This provides a definition for Bar<N>::i
for N not equal to 2 or 3.
这篇关于初始化模板化类的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!