“模板不支持分离编译”
首先,创建一个.h文件和两个.cpp文件
//template.h文件
#include<iostream>
using namespace std;
void F1();
//template.cpp文件
#include "template.h"
void F1()
{
cout << "F1()" << endl;
}
//test.cpp文件
#include "template.h"
int main()
{
F1();
return 0;
}
运行结果如图所示:
定义一个模板函数F2(),代码如下所示:
//template.h
#include<iostream>
using namespace std;
void F1();
template<class T>
void F2(const T&x);
//template.cpp
#include "template.h"
void F1()
{
cout << "F1()" << endl;
}
template<class T>
void F2(const T& x)
{
cout << "F2(x)" << endl;
}
//test.cpp
#include "template.h"
int main()
{
F1();
F2(10);
return 0;
}
运行结果如下图所示:
编译不能通过,由LINK可看出为链接错误,下面对代码运行过程进行简要的分析。
代码运行需经过四个步骤:
1)预处理:头文件展开,宏替换,条件编译,去掉注释。
2)编译:检查语法,生成汇编代码。
3)汇编:将汇编代码转换成机器码。
4)链接:进行整合。
对上述代码进行分析得:
因为是链接错误,所以可知问题出在两个.o文件进行整合时。
解决方法:
1)显示实例化
2)将模板函数放到.h文件中
代码如下:
//Template.h
#include<iostream>
using namespace std;
void F1();
template<class T>
void F2(const T &x)
{
cout << "F2(x)" << endl;
}
//Template.cpp
#include "template.h"
void F1()
{
cout << "F1()" << endl;
}
//Test.cpp
#include "template.h"
int main()
{
F1();
F2(10);
return 0;
}
运行结果如图所示: