在正常情况下,c++模板是不允许在头文件声明,在cpp文件中实现。那是因为在cpp文件在编译时内存必须要给它分配储存空间。但是模板本身是一种泛型,在没有明确定义声明类型前,编译器也无法知道它的大小。所以就会出现链接失败。
//print.h
#ifndef _PRINT_
#define _PRINT_
template<typename T>
void print(T obj);
#endif
//print.cpp
#include "print.h"
#include <iostream>
using namespace std;
template<typename T>
void print(T obj)
{
cout<<obj;
}
//main.cpp
#include"print.h"
int main()
{
print(100);
while(1);
return 0;
}
如果这样子编译的话,就会提示:
1>LINK : E:\mycode\模板\Debug\模板分离.exe not found or not built by the last incremental link; performing full link
1>main.obj : error LNK2019: unresolved external symbol "void __cdecl print<int>(int)" (??$print@H@@YAXH@Z) referenced in function _main
1>E:\mycode\模板\Debug\模板分离.exe : fatal error LNK1120: 1 unresolved externals
常用的解决方法一共有2种:
1是将定义也在头文件中,这种就不用说了。由于不在cpp文件中定义编译器也没有必要一开始分配内存,也就不会报错。
2采用显式的实例化声明,刚才我说过,定义在cpp文件中的模板函数由于没有确定的类型,导致编译器无法分配内存。这时候只要给以确定的类型,也就是显式的实例化声明就可以了,只需要在头文件中用确定的类型再声明一次即可。
//print.h
#ifndef _PRINT_
#define _PRINT_
template<typename T>
void print(T obj);
template void print<int>(int);
#endif
这样在编译就能通过了。
原文链接: https://www.cnblogs.com/ssss429170331/p/5593282.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/235354
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!