C++模板类头文件和实现文件分离

时间:2023-03-09 02:20:01
C++模板类头文件和实现文件分离

http://www.cnblogs.com/lvdongjie/p/4288373.html

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

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

问题的提出:(帖子在:http://topic.****.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中:

  1. #ifdef FUCK
  2. template<class T>
  3. T 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. T 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不支持“分别编译”模型。