【C++】类型萃取

为什么要用到类型萃取?

在C++中,想要对数据进行拷贝的话,通常有两种情况

  1. 内置类型
  2. 自定义类型

对于内置类型,我们可以使用memmove或memcpy来进行拷贝

而对于自定义类型,我们需要使用赋值的方式来进行拷贝

示例代码如下:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值