c++ 泛型 之 TypeTraints

完整代码 在 

 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;
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值