templates — C++模板的應用

http://www.verydemo.com/demo_c128_i6615.html

奇特的遞歸模板模式(CRTP)這個奇特的名字代表了類實現技術中一種通用的模式,即派生類將本身作爲模板參數傳遞給基類;

CRTP的一個簡單的應用是記錄某個類的對象構造的總個數。數對象個數很簡單,只需引入一個整數類型的靜態數據成分,分別在構造與析構中進行遞增與遞減操作,不過,要在每個類中都這麼寫非常繁瑣,有了CRTP,我們可以寫入一個模板來實現;

實例代碼:

  1. #include <iostream>  
  2. #include <stddef.h>  
  3.   
  4. //CRTP template class object  
  5. template <typename CountedType>  
  6. class ObjectCounter{  
  7. private:  
  8.     static size_t count;  
  9. protected:  
  10.     ObjectCounter(){  
  11.         ++ObjectCounter<CountedType>::count;  
  12.     };  
  13.     ObjectCounter(ObjectCounter<CountedType> const&){  
  14.         ++ObjectCounter<CountedType>::count;  
  15.     }  
  16.     ~ObjectCounter(){  
  17.         --ObjectCounter<CountedType>::count;  
  18.     }  
  19.   
  20. public:  
  21.     static size_t _live(){  
  22.         return ObjectCounter<CountedType>::count;  
  23.     }  
  24. };  
  25.   
  26. template <typename CountedType>  
  27. size_t ObjectCounter<CountedType>::count = 0;  
  28.   
  29.   
  30. template <typename CharT>  
  31. class MyString : public ObjectCounter<MyString<CharT> >{  
  32.   
  33. };  
  34.   
  35.   
  36. int _tmain(int argc, _TCHAR* argv[])  
  37. {  
  38.     MyString<char> s1, s2;  
  39.     MyString<wchar_t> ws;  
  40.   
  41.     std::cout << MyString<char>::_live() << std::endl;  
  42.     std::cout << MyString<char>::_live() << std::endl;  
  43.     std::cout << MyString<wchar_t>::_live() << std::endl;  
  44.   
  45.     getchar();  
  46.   
  47.     return 0;  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章