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 @   Jake Lin  阅读(667)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示