2.10.1
實作出Pointer Traits
大部分type
traits的實作都依賴全特化或偏特化。下面代碼用來判斷型別T是否為指針:
1 template<typename T>
2 class TypeTraits
3 {
4 private:
5 template<class U> struct PointerTraits
6 {
7 enum { result = false };
8 typedef NullType PointeeType;
9 };
10 template<class U> struct PointerTraits<U*>
11 {
12 enum { result = true };
13 typedef U PointeeType;
14 };
15 public:
16 enum { isPointer = PointerTraits<T>::result };
17 typedef PointerTraits<T>::Pointeetype PointeeType;
18 };
對于一個指針型別,PointerTraits的偏特化版本更適合。所以對于一個非指針型別,result為false,所謂被指型別PointeeType不能拿來使用,只是一個不能被使用的占位型別(placeholder type)。
對于指向成員函數的指針,我們需要這樣做:
1 template<typename T>
2 class TypeTraits
3 {
4 private:
5 template <class U> struct PToMTraits
6 {
7 enum{result = false};
8 };
9 template <class U, class V>
10 struct PToMTraits<U, V::*>
11 {
12 enum {reulst = true };
13 }
14 public:
15 enum { isMemberPointer = PToMTraits<T>::result};
16 };
17