zoukankan      html  css  js  c++  java
  • 实现C++模板类头文件和实现文件分离的方法

     

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

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

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

    第一种方法:按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中:

    [c-sharp] view plaincopyprint?
     
    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中:

    [c-sharp] view plaincopyprint?
     
    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"

    [c-sharp] view plaincopyprint?
     
    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不支持“分别编译”模型。

  • 相关阅读:
    第二十天笔记
    第十九天笔记
    第十七天笔记
    第十五天笔记
    第十六天笔记
    第十二天笔记
    数字三角形
    最大子段和与最大子矩阵和
    分组背包
    二维背包
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/4288373.html
Copyright © 2011-2022 走看看