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):「除非顯式實例化或明確指定了可變模板專門化,否則可變模板當專業化被使用時,專業化被隱含地實例化「 –