下面這個代碼出錯:
//test.h template<typename T> void fun(T x);
//test.cpp #include "test.h" template<typename T> void fun(T x) { std::cout<<x<<std::endl; }
//main.cpp #include<iostream> #include "test.h" int main() { int i=1; fun(i); return 0; }
結果分別編譯時沒問題,連接時報錯:
Linking... main.obj : error LNK2001: unresolved external symbol "void __cdecl fun
解決辦法,將模板函數的定義放到頭文件中:
//test.h #include<iostream> template<typename T> void fun(T x) { std::cout<<x<<std::endl; }
OK
{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"typ
{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragr
{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null