完整代碼 在
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
測試
void typetraits_test()
{
const bool isPointer = TypeTraints<std::vector<int>::iterator>::isPointer;
}