How to separate the implementation and definition for template function in c++
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(Jake's Blog on 博客园)
出处:http://procoder.cnblogs.com
本作品由Jake Lin创作,采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问或者授权方面的协商,请给我留言。
出处:http://procoder.cnblogs.com
本作品由Jake Lin创作,采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问或者授权方面的协商,请给我留言。