在VC9.0中实现C++模板类头文件和实现文件分离的方法

如何实现C++模板类头文件和实现文件分离,这个问题和编译器有关。

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

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

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

 

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.     base() {};  
  6.     ~base() {};  
  7.     T add_base(T x,T y);  
  8. };  
  9. #include "template_compile.cpp"  
 

 

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

 

  1. template<class T>  
  2. T base<T>::add_base(T x,T y)  
  3. {  
  4.     return x+y;  
  5. }  
 

 

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

 

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

 

这种方法不能通过编译,"template_compile.cpp"文件不能"看见"“template_compile.h"文件。

然而:如果我把类模板的实现文件里代码放在类模板的头文件中,注释掉:#include "template_compile.cpp",编译和运行不会有任何错误。理论上”把类模板的实现文件里代码放在类模板的头文件中“和”在定义模板类的头文件中的末行用语句:#include "template_compile.cpp" “是一致的,但编译器就是通不过。

实验证明:VC9.0不支持C++primer中所说的“包含”模型。

第二种方法:bruceteen提出的:使用define

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

 

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.   base() {};  
  6.   ~base() {};  
  7.   T add_base(T x,T y);  
  8. };  
  9. #define FUCK  
  10. #include "template_compile.cpp"  
 

 

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

 

  1. #ifdef FUCK  
  2. template<class T>  
  3. base<T>::add_base(T x,T y)  
  4. {  
  5.   return x+y;  
  6. }  
  7. #endif  
 

 

测试文件不变。

实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离

方法三:

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

 

  1. template<class T>  
  2. class base  
  3. {  
  4. public:  
  5.     base() {};  
  6.     ~base() {};  
  7.     T add_base(T x,T y);  
  8. };  
 

 

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

 

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

 

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

 

  1. #include<iostream>  
  2. #include "template_compile.cpp"  
  3. using namespace std;  
  4. void main()  
  5. {  
  6.     base<int> bobj;  
  7.     cout<<bobj.add_base(2,3)<<endl;  
  8. }  
 

 

实验证明:在VC9.0中,这种方法可以实现类模板头文件和实现文件的分离。

另外实验证明:VC9.0不支持“分别编译”模型。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值