4
下面的代码如何正确工作?“不完整”对象实例化和输出行为
#include <cstdio>
template<class T>
T x = T{};
void foo()
{
class Test
{
public:
Test() { std::printf("Test::Test\n"); }
};
Test t = x<Test>;
}
int main()
{
std::printf("main\n");
}
输出
Test::Test
main
- 为什么它打印
Test::Test
第一,而不是main
? - 它依赖哪个标准?仅仅是C++ 1z吗?我无法找到相关的提案。你能给我一个链接吗?
- 什么是
x
在这段代码和Test t = x<Test>
如何实际工作?
而且,如果我改变std::printf
调用std::cout
整个程序崩溃:
#include <iostream>
template<class T>
T x = T{};
void foo()
{
class Test
{
public:
Test() { std::cout << "Test::Test\n"; }
};
Test t = x<Test>;
}
int main()
{
std::cout << "main\n";
}
输出
Segmentation fault (core dumped) ./a.out
为什么?
Google“变量模板”。 –
@sleep紧pup Ok好的,谢谢。为什么它实例化没有调用'foo'函数呢? – FrozenHeart
[tmp.inst/5](http://eel.is/c++draft/temp#variable%20template!definition~of):“除非显式实例化或明确指定了可变模板专门化,否则可变模板当专业化被使用时,专业化被隐含地实例化“ –