C++ template模板函数的定义与调用

引用《C++primer(第四版)》里的观点:
1)标准C++为编译模板代码定义了两种模型:“包含”模型和“分别编译”模型。
2)所有编译器都支持“包含”模型,某些编译器支持“分别编译”模型。

问题的提出:(帖子在:http://topic.csdn.net/u/20101215/15/f4f270f2-f0f9-4c5f-8765-1bfde2aeebbf.html

方法一:

声明和实现都放在头文件里。

在类模板头文件template_compile.h中:

template<class T>  
class base  
{  
public:  
    base() {};  
    ~base() {};  
    T add_base(T x,T y);  
};  

template<class T>  
T base<T>::add_base(T x,T y)  
{  
    return x+y;  
} 

在使用模板的测试文件use_template.cpp中:

#include<iostream>  
#include "template_compile.h"  
using namespace std;  
void main()  
{  
    base<int> bobj;  
    cout<<bobj.add_base(2,3)<<endl;  
}  

方法二:

按C++primer中的“包含”模型,在定义模板类的头文件中的末行用语句:#include “template_compile.cpp”

在类模板头文件template_compile.h中:

template<class T>  
class base  
{  
public:  
    base() {};  
    ~base() {};  
    T add_base(T x,T y);  
};  
#include "template_compile.cpp"  

在类模板的实现文件template_compile.cpp中:

template<class T>  
T base<T>::add_base(T x,T y)  
{  
    return x+y;  
} 

测试文件不变。

方法三

使用define

在类模板头文件template_compile.h中:

template<class T>  
class base  
{  
public:  
  base() {};  
  ~base() {};  
  T add_base(T x,T y);  
};  
#define TEMP  
#include "template_compile.cpp"  

在类模板的实现文件template_compile.cpp中:

#ifdef TEMP  
template<class T>  
T base<T>::add_base(T x,T y)  
{  
  return x+y;  
}  
#endif  

测试文件不变。

方法四

在类模板头文件template_compile.h中:

template<class T>  
class base  
{  
public:  
    base() {};  
    ~base() {};  
    T add_base(T x,T y);  
};

在类模板的实现文件template_compile.cpp中:

#include "template_compile.h"  
template<class T>  
T base<T>::add_base(T x,T y)  
{  
    return x+y;  
}  

在使用模板的测试文件use_template.cpp中:使用#include “template_compile.cpp”

#include<iostream>  
#include "template_compile.cpp"  
using namespace std;  
void main()  
{  
    base<int> bobj;  
    cout<<bobj.add_base(2,3)<<endl;  
}  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值