博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How to separate the implementation and definition for template function in c++
阅读量:7163 次
发布时间:2019-06-29

本文共 1116 字,大约阅读时间需要 3 分钟。

When I use template function in my class TestClass. The complier will throw out a Link Error below.

TestClass.h 

template
T foo(T a, T b);

TestClass.cpp 

   

template
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)" (??$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
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,如需转载请自行联系原作者

你可能感兴趣的文章