When I use template function in my class TestClass. The complier will throw out a Link Error below.
TestClass.h
template<class T>
T foo(T a, T b);
TestClass.cpp
template<class T>
T TestClass::foo(T a, T b)
{
return a;
}
Client.cpp
TestClass testClass;
testClass.foo(0, 1);
Link Error
Error 1 error LNK2019: unresolved external symbol "public: int __cdecl TestClass::foo<int>(int,int)" (??$foo@H@TestClass@@QAAHHH@Z) referenced in function "private: bool __cdecl Client::TestFunction()" (?TestFunction@Client@@@Z) Client.obj
There are some approach we can use to fix this issue. I prefer to use the implementation header to fix that issue.
Add a new file called TestClass_impl.h and move all the template functions from TestClass.cpp to TestClass_impl.h
Include TestClass_impl.h into TestClass.h
TestClass.h
class TestClass
{
template<class T>
T foo(T a, T b);
};
#include "TestClass_impl.h"
All done.
本文转自Jake Lin博客园博客,原文链接:http://www.cnblogs.com/procoder/archive/2010/06/29/How-to-Separate-the-Implementation-and-Definition-of-Template-Function-in-CPP.html,如需转载请自行联系原作者