C++模板分离

在正常状况下,c++模板是不容许在头文件声明,在cpp文件中实现。那是由于在cpp文件在编译时内存必需要给它分配储存空间。可是模板自己是一种泛型,在没有明肯定义声明类型前,编译器也没法知道它的大小。因此就会出现连接失败。ios

//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;
}

若是这样子编译的话,就会提示:c++

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文件中定义编译器也没有必要一开始分配内存,也就不会报错。ui

2采用显式的实例化声明,刚才我说过,定义在cpp文件中的模板函数因为没有肯定的类型,致使编译器没法分配内存。这时候只要给以肯定的类型,也就是显式的实例化声明就能够了,只须要在头文件中用肯定的类型再声明一次便可。spa

//print.h
#ifndef _PRINT_
#define _PRINT_

template<typename T> 
void print(T obj);

template void print<int>(int);
#endif

这样在编译就能经过了。code

相关文章
相关标签/搜索