在包含编译模型中,编译器必须看到用到的所有模板的定义。一般而言,可以通过在声明模板函数或类模板的头文件中添加一条#include指示使定义可用,该#include引入了包含相关定义的源文件。
1 tt.h
#ifndef TT_H
#define TT_H
#include <iostream>
using namespace std;
template <class T> int compare(const T&,const T&);
#include "tt.cpp"
#endif
2.tt.cpp
template <typename T> int compare(const T &v1, const T &v2)
{
if(v1 < v2)
return -1;
if(v1 > v2)
return 1;
return 0;
}
3.main.cpp
#include "tt.h"
int main()
{
int i=0;
i=compare(1,2);
cout<<i<<endl;
return 0;
}