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.
原文链接: https://www.cnblogs.com/procoder/archive/2010/06/29/How-to-Separate-the-Implementation-and-Definition-of-Template-Function-in-CPP.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/12305
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!