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博客园博客,原文链接:http://www.cnblogs.com/procoder/archive/2010/06/29/How-to-Separate-the-Implementation-and-Definition-of-Template-Function-in-CPP.html,如需转载请自行联系原作者


相关文章
|
JavaScript
Vue 报错Failed to mount component: template or render function not defined
Vue 报错Failed to mount component: template or render function not defined
Vue 报错Failed to mount component: template or render function not defined
|
JavaScript
uniapp:[Vue warn]: Failed to mount component: template or render function not de
uniapp:[Vue warn]: Failed to mount component: template or render function not de
365 0
uniapp:[Vue warn]: Failed to mount component: template or render function not de
|
JavaScript
uniapp:[Vue warn]: Failed to mount component: template or render function not defined. found in
uniapp:[Vue warn]: Failed to mount component: template or render function not defined. found in
1037 0
uniapp:[Vue warn]: Failed to mount component: template or render function not defined. found in
Matlab:成功解决Function definition are not permitted at the prompt or scripts
Matlab:成功解决Function definition are not permitted at the prompt or scripts
definition of dllimport function not allowed 错误
definition of dllimport function not allowed 不允许dllimport函数的定义 本应该是导出,结果写成导入了,就会出现这个问题 改为:dllexport 问题解决。
1056 0
|
8月前
|
人工智能 Python
083_类_对象_成员方法_method_函数_function_isinstance
本内容主要讲解Python中的数据类型与面向对象基础。回顾了变量类型(如字符串`str`和整型`int`)及其相互转换,探讨了加法在不同类型中的表现。通过超市商品分类比喻,引出“类型”概念,并深入解析类(class)与对象(object)的关系,例如具体橘子是橘子类的实例。还介绍了`isinstance`函数判断类型、`type`与`help`探索类型属性,以及`str`和`int`的不同方法。最终总结类是抽象类型,对象是其实例,不同类型的对象有独特运算和方法,为后续学习埋下伏笔。
164 7
083_类_对象_成员方法_method_函数_function_isinstance

热门文章

最新文章