完整代码 在
http://download.csdn.net/detail/zhuyingqingfen/8457091
#ifndef TYPETRAITS_H_ #define TYPETRAITS_H_ //只有声明,没有定义,它只能被用来表示“我不是个令人感兴趣的型别”。 class NullType; //这是一个可被继承的合法型别,而且你可以传递EmptyType对象。 class EmptyType{}; //1. 常整数 映射为型别 /* 根据不同的数值产生不同的型别。一般而言,符合下列条件便可使用Int2Type 1. 有必要根据某个编译期常数调用一个或数个不同的函数 2. 有必要在编译期实施“分派”(dispatch)(if else 型分派要求每个条件都要编译通过,而通过 Int2Type不会产生类似问题,因为编译期不会去编译一个未被使用到的template函数(如果一个template的 成员函数未曾被真正使用上,c++不会将它具现化)。 */ template<int v> struct Int2Type { enum{value = v}; }; //Type2Type 唯一作用就是消除重载函数的歧义(模棱两可)。 //////////////////////////////////////////////////////////////////////////////// // class template Type2Type // Converts each type into a unique, insipid type // Invocation Type2Type<T> where T is a type // Defines the type OriginalType which maps back to T //////////////////////////////////////////////////////////////////////////////// template <typename T> struct Type2Type { typedef T OriginalType; }; //型别选择,根据第一个引数判断是用第二个参数还是第三个参数 template<bool flag,typename T,typename U> struct Select { typedef T Result; }; template<typename T,typename U> struct Select<false,T,U> { typedef U Result; }; //Type Traits template <class T> class TypeTraints { private: template<class U>struct PointerTraints { enum{result = false}; typedef NullType PointerType; }; template<class U>struct PointerTraints<U*> { enum{result = true;}; typedef U PointerType; }; template<class U>struct PtoMTraits { enum{result = false}; }; template<class U,class V> struct PtoMTraits<U V::*> { enum{result = true}; }; public: enum { isPointer = PointerTraints<T>::result, isMemberPointer = PtoMTraits<T>::result }; typedef typename PointerTraints<T>::PointerType PointerType; }; #endif
原文地址:http://blog.csdn.net/zhuyingqingfen/article/details/43938673