C++ 中模板类中的静态字段初始化
我正在尝试用 C++ 创建一些自注册类。因此,我尝试了与此处提供的解决方案类似的解决方案。在这样做的过程中,我偶然发现了一些奇怪的事情。
代码如下:
#include <iostream>
class StaticClassType {
public:
StaticClassType() {
// Notify when the static member is created
std::cout << "We're in." << std::endl;
}
};
template<typename T>
class TestClass1 {
public:
TestClass1() { &m; }
private:
// Static member in a template class
static StaticClassType m;
};
template<typename T>
StaticClassType TestClass1<T>::m;
class TestClass2 : public TestClass1<TestClass2> {
public:
TestClass2() { } // required; why?
};
int main() {
return 0;
}
此代码在启动时创建静态成员变量 TestClass1::m
(从而将“We're in.”打印到控制台) - 即在 main()
之前> 已启动。但是,只有当我为 TestClass2
编写一个(空)构造函数时,该代码才有效(如示例所示)。
为什么我需要编写这个构造函数?为什么编译器生成的默认构造函数不做同样的事情?
此问题仅发生在模板类中。如果 TestClass1
不是模板类,则代码无需为 TestClass2
编写空构造函数即可运行。
I'm trying to create some self-registering classes in C++. So I tried the solution similar to the one provided here. While doing this I stumble over something strange.
Here's the code:
#include <iostream>
class StaticClassType {
public:
StaticClassType() {
// Notify when the static member is created
std::cout << "We're in." << std::endl;
}
};
template<typename T>
class TestClass1 {
public:
TestClass1() { &m; }
private:
// Static member in a template class
static StaticClassType m;
};
template<typename T>
StaticClassType TestClass1<T>::m;
class TestClass2 : public TestClass1<TestClass2> {
public:
TestClass2() { } // required; why?
};
int main() {
return 0;
}
This code create the static member variable TestClass1::m
on startup (thereby printing "We're in." to the console) - i.e. before main()
is started. However, the code only works if I write a (empty) constructor for TestClass2
(as shown in the example).
Why do I need to write this constructor? Why doesn't the default constructor generated by the compiler does the same thing?
This problem only occurs for template classes. If TestClass1
wasn't a template class, the code would work without writing the empty constructor for TestClass2
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我创建了更小的示例(没有构造函数,不需要):
请注意,需要 foo() 方法,否则编译器将删除静态变量,因为它没有在任何地方使用。
I created even smaller example (without constructors, which are not needed) :
take a note that foo() method is needed, otherwise the compiler removes the static variable, since it's not used anywhere.
从我的角度来看,“问题”是在“模板世界”中,编译器将仅生成客户端代码真正使用的内容。在这里,您永远不会实例化 TestClass2 类。因此不会生成很多代码。尝试一下:
然后就可以了。
From my point of view the "issue" is that in "Template world" the compiler will generate only what is really used by the client code. Here You never instanciate the TestClass2 class. Therefore a lot of code won't be generated. Try :
And it works then.