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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值