如果模板已经被实例化,可以通过外部模板声明,防止模板被多次实例化,从而降低编译和链接的时间成本:
//头文件t.h
#include <iostream>
template<class T>//定义模板函数
void pValue(T t)
{
std::cout<<"The value is "<<t<<std::endl;
}
//b.cpp
#include "t.h"
//在当前编译单元内,显示实例化(强制实例化)函数模板
template void pValue<int>(int);
void pInt(int d)
{
pValue(d);//对函数模板的实例进行调用
}
//m.cpp
#include "t.h"
//函数模板的外部声明,指明该函数模板已经在别的编译单元被实例化,因此在当前编译单元无需实例化
extern template void pValue<int>(int);
//声明定义于b.cpp的函数
void pInt(int d);
int main()
{
pValue(1);
pInt(2);
return 0;
}