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.


posted @ 2010-06-29 20:46  Jake Lin  阅读(663)  评论(0编辑  收藏  举报