【发布时间】:2011-10-21 00:58:19
【问题描述】:
有很多关于何时调用普通类的静态成员的构造函数的信息。但是,我看到一些关于模板类的奇怪行为。
以下程序的输出应该是什么? (注意我使用 printf 来避免 std::cout 的任何静态初始化命令失败并发症。)
#include <iostream>
class B {
public:
B(const std::string &s) { printf("Hello I am B from %s\n", s.c_str()); }
};
template<typename T>
class Atempl {
public:
static B b_;
};
class A {
public:
static B b_;
};
template<typename T>
B Atempl<T>::b_("Atempl");
B A::b_("A");
class C : public Atempl<int> {
};
int main(int argc, const char *argv[]) {
return 0;
}
我认为输出应该是:
Hello I am B from A
Hello I am B from Atempl
但是在 FreeBSD 7.3 上使用 g++ 4.3 我得到:
Hello I am B from A
如果我添加行
template class Atempl<int>;
一切都很好,我得到了预期的输出。问题是,为什么类 C 的声明不能算作模板的实例化 阿坦普尔 并导致 B 的构造函数被调用?这是标准的一部分还是 g++ 4.3 中的错误?
【问题讨论】:
标签: c++ templates constructor static-members