一、模板为什么不能分离编译?
普通函数
template.h:
#pragma once
#include<iostream>
using namespace std;
void Func();
template.cpp:
#include"template.h"
void Func()
{
cout << "普通函数" << endl;
}
test.cpp:
#include"template.h"
int main()
{
Func();
system("pause");
return 0;
}
运行结果:
分析:
分离编译后程序正常执行。
模板函数
template.h:
#pragma once
#include<iostream>
using namespace std;
void Func();
template<class T>
void TFunc(const T& a);
template<class T>
class TClass
{
public:
TClass();
};
template.cpp
#include"template.h"
void Func()
{
cout << "普通函数" << endl;
}
template<class T>
void TFunc(const T& a)
{
cout << "模板函数" << endl;
}
template<class T>
TClass<T>::TClass()
{
cout << "模板类" << endl;
}
//显示实例化
template
void TFunc<int>(const int& a);
template
void TFunc<double>(const double& a);
template class TClass<int>;
test.cpp
#include"template.cpp"//既有声明也有定义
int main()
{
Func();
TFunc(10);
TFunc(1.111);
TClass<int> t;
system("pause");
return 0;
}
模板函数报错结果:
模板类报错结果:
模板无法生成对象,只有实例化后才能生成代码。
分离后压根就.h文件夹里没有实例化的对象,实例化是在另外一个cpp,两个cpp不会交互,不会实例化出对象,所以模板不能进行 分离编译
二、怎样解决这个问题?
1、进行显示实例化
缺陷:只能实例化出一种类型
template.cpp中生成一个obj
test.cpp中也生产一个obj
2、最好的方式是把声明和定义放一个头文件里