类型萃取

         在C++中,我们可以通过typeid来获取一个类型的名称,但是不能拿来做变量的声明。在C++中,我们可以通过类型萃取的方式来对内置类型和普通类型进行区分。例如将要看到的例子,如果是内置类型,string类存在浅拷贝的问题,所以必须采用值拷贝,若不是内置类型,则可调用memove拷贝函数来进行拷贝。

struct TrueType
{
	bool Get()
	{
		return true;
	}
};
struct FalseType
{
	bool Get()
	{
		return false;
	}
};
template<typename T>
struct TypeTraits
{
	typedef FalseType IsPODType;        
};
//将所有内置类型特化  
template<>
struct TypeTraits<int>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<unsigned int>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<short>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<unsigned short>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<char>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<unsigned char>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<float>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<double>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<long>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<long double>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<unsigned long>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<long long>
{
	typedef TrueType IsPODType;          
};
template<>
struct TypeTraits<unsigned long long>
{
	typedef TrueType IsPODType;          
};


template<typename T>
void Copy(T* dest, T* src, int sz)
{
	if (TypeTraits<string>::IsPODType().Get() == 1)//如果是内置类型  
	{
		memmove(dest, src, sz*sizeof(T));           //对于string存在浅拷贝的问题,所以string必须用值拷贝  
	}
	else         //如果不是内置类型  
	{
		for (int i = 0; i < sz; i++)
		{
			dest[i] = src[i];
		}
	}
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值