C++模板類頭文件和實現文件分離


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

 

如何實現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中:

 

[cpp]  view plain copy print ?
 
  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中:

 

[cpp]  view plain copy print ?
 
  1. template<class T>  
  2. T base<T>::add_base(T x,T y)  
  3. {  
  4.     return x+y;  
  5. }  
 

 

在使用模板的測試文件use_template.cpp中:

 

[cpp]  view plain copy print ?
 
  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中:

 

[cpp]  view plain copy print ?
 
  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 plain copy print ?
 
  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中:

 

[cpp]  view plain copy print ?
 
  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 plain copy print ?
 
  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 plain copy print ?
 
  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不支持“分別編譯”模型。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM