C++模板编译模型:包含编译模型

来源:互联网 发布:安卓平台c语言编译器 编辑:程序博客网 时间:2024/04/28 00:04

 

    在包含编译模型中,编译器必须看到用到的所有模板的定义。一般而言,可以通过在声明模板函数或类模板的头文件中添加一条#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;
}