有了前面3篇文章的基礎,再看這篇文章就很容易了
這是Loki裏的類型識別的測試,分別測試普通類型,指針類型和類成員指針類型。
下面是測試代碼,測試環境是gcc 4.6.3
NullType.h
- #ifndef _NULLTYPE_INC_
- #define _NULLTYPE_INC_
- class NullType;
- #endif
PointerTraits.h
- #ifndef _POINTERTRAITS_INC
- #define _POINTERTRAITS_INC
- #include "NullType.h"
- template <typename T>
- class TypeTraits
- {
- private:
- template <class U> struct PointerTraits
- {
- enum {result = false};
- typedef NullType PointeeType;
- };
- template <class U> struct PointerTraits<U*>
- {
- enum {result = true};
- typedef U PointeeType;
- };
- template <class U> struct PToMTraits
- {
- enum {result = false};
- };
- template <class U, class V> struct PToMTraits<U V::*>
- {
- enum {result = true};
- };
- public:
- enum {isPointer = PointerTraits<T>::result};
- typedef typename PointerTraits<T>::PointeeType PointeeType;
- enum {isMemberPointer = PToMTraits<T>::result};
- };
- #endif
main.cpp
- #include <iostream>
- #include <vector>
- using namespace std;
- #include "PointerTraits.h"
- class T
- {
- public:
- int a;
- };
- int main(int argc, char *argv[])
- {
- bool iterIsPtr = TypeTraits<vector<int>::iterator>::isPointer;
- cout<<"vector<int>::iterator is "<<(iterIsPtr ? "pointer": "type")<<"\n";
- iterIsPtr = TypeTraits<int*>::isPointer;
- cout<<"int* is "<<(iterIsPtr ? "pointer": "type")<<"\n";
- iterIsPtr = TypeTraits<int*>::isMemberPointer;
- cout<<"int* is member pointer ("<<(iterIsPtr ? "yes": "no")<<")\n";
- /*
- * int T::* 是一個指向類T的int的指針。
- * 如:int T::* c = &T::a;
- */
- //int T::* c = &T::a;
- iterIsPtr = TypeTraits<int T::*>::isMemberPointer;
- cout<<"int* is member pointer ("<<(iterIsPtr ? "yes": "no")<<")\n";
- return 0;
- }
編譯:g++ main.cpp
運行:./a.out
輸出:
vector<int>::iterator is typeint* is pointer
int* is member pointer (no)
int T::* is member pointer (yes)