c++ 運行期類型識別

有了前面3篇文章的基礎,再看這篇文章就很容易了



這是Loki裏的類型識別的測試,分別測試普通類型,指針類型和類成員指針類型。


下面是測試代碼,測試環境是gcc 4.6.3

NullType.h

  1. #ifndef _NULLTYPE_INC_  
  2. #define _NULLTYPE_INC_  
  3.   
  4. class NullType;  
  5.   
  6. #endif  


PointerTraits.h

  1. #ifndef _POINTERTRAITS_INC  
  2. #define _POINTERTRAITS_INC   
  3.   
  4. #include "NullType.h"  
  5.   
  6. template <typename T>  
  7. class TypeTraits  
  8. {  
  9. private:  
  10.     template <class U> struct PointerTraits  
  11.     {  
  12.         enum {result = false};  
  13.         typedef NullType PointeeType;  
  14.     };  
  15.   
  16.     template <class U> struct PointerTraits<U*>  
  17.     {  
  18.         enum {result = true};  
  19.         typedef U PointeeType;  
  20.     };  
  21.   
  22.     template <class U> struct PToMTraits  
  23.     {  
  24.         enum {result = false};  
  25.     };  
  26.   
  27.     template <class U, class V> struct PToMTraits<U V::*>  
  28.     {  
  29.         enum {result = true};  
  30.     };  
  31.   
  32. public:  
  33.     enum {isPointer = PointerTraits<T>::result};  
  34.     typedef typename PointerTraits<T>::PointeeType PointeeType;  
  35.   
  36.     enum {isMemberPointer = PToMTraits<T>::result};  
  37. };  
  38.   
  39.   
  40. #endif  

main.cpp

  1. #include <iostream>  
  2. #include <vector>  
  3. using namespace std;  
  4.   
  5. #include "PointerTraits.h"  
  6.   
  7. class T  
  8. {  
  9. public:  
  10.     int a;  
  11. };  
  12.   
  13. int main(int argc, char *argv[])  
  14. {  
  15.     bool iterIsPtr = TypeTraits<vector<int>::iterator>::isPointer;  
  16.     cout<<"vector<int>::iterator is "<<(iterIsPtr ? "pointer""type")<<"\n";  
  17.   
  18.     iterIsPtr = TypeTraits<int*>::isPointer;  
  19.     cout<<"int* is "<<(iterIsPtr ? "pointer""type")<<"\n";  
  20.   
  21.     iterIsPtr = TypeTraits<int*>::isMemberPointer;  
  22.     cout<<"int* is member pointer ("<<(iterIsPtr ? "yes""no")<<")\n";  
  23.   
  24.     /* 
  25.      * int T::* 是一個指向類T的int的指針。 
  26.      * 如:int T::* c = &T::a; 
  27.      */  
  28.   
  29.     //int T::* c = &T::a;  
  30.     iterIsPtr = TypeTraits<int T::*>::isMemberPointer;  
  31.     cout<<"int* is member pointer ("<<(iterIsPtr ? "yes""no")<<")\n";  
  32.   
  33.     return 0;  
  34. }  

編譯:g++ main.cpp

運行:./a.out

輸出:

vector<int>::iterator is type
int* is pointer
int* is member pointer (no)
int T::* is member pointer (yes)

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