类型萃取

在C++中我们可以通过typeid来获取一个类型的名称(内置类型和自定义类型都可以)但是我们不能用这种方式获取来的名称做变量的声明。这就用到了类型萃取。

例如:我们在Seqlist中要用到类型萃取,因为内置类型我们可以通过memmove进行拷贝,例如string类我们要通过赋值的方式进行拷贝。

类型萃取原理:在模板的基础上区分内置类型和其他类型,主要原理是将内置类型全部特化,然后再进行区分

struct TrueType
{
	bool Get()
	{
		return true;
	}
};
struct FalseType
{
	bool Get()
	{
		return false;
	}
};
template<class T>
struct TypeTraits
{
	typedef FalseType IsPODType;
};
template<>//对内置类型进行特化
struct TypeTraits<int>
{
	typedef TrueType IsPODType;//如果内置类型就为TrueType
};

template <class T>
void TypeCopy(T*dst, const T*src,size_t n)
{
	if (TypeTraits<T>::IsPODType().Get()== true)//类型萃取
	{
		cout << "memmove" << endl;
		memmove(dst, src, n*sizeof(T));
	}
	else
	{
		cout << "for" << endl;
		for (int i = 0; i < n; i++)
		{
			dst[i] = src[i];
		}
	}
}
int main()
{
	string a1[5] = { "11", "22", "33" };
	string a2[5] = { "111", "222", "333" };
	int arr1[5] = { 1, 2, 3 };
	int arr2[5] = { 2, 3, 4 };
	TypeCopy(a1, a2, 3);
	TypeCopy(arr1, arr2, 3);
	system("pause");
	return 0;



struct TrueType
{
};
struct FalseType
{
};
template<class T>
struct TypeTraits
{
	typedef FalseType IsPODType;
};
template<>//对内置类型进行特化
struct TypeTraits<int>
{
	typedef TrueType IsPODType;//如果内置类型就为TrueType
};

template<class T>
void* Copy(T*dst, T*src, size_t n, FalseType a)
{
	cout << "for" << endl;
	for (int i = 0; i < n; i++)
	{
		dst[i] = src[i];
	}
	return dst;
}
template<class T>
void* Copy(T*dst, T* src, size_t n, TrueType a)
{
	cout << "memmove" << endl;
	return memmove(dst, src, n*sizeof(T));
}
template<class T>
void* TypeCopy(T*dst,  T* src, size_t n)
{
	
    return Copy(dst,  src,  n,TypeTraits<T>::IsPODType());//TrueType类型或FalseType类型对象
}

int main()
{
	string a1[5] = { "11", "22", "33" };
	string a2[5] = { "111", "222", "333" };
	int arr1[5] = { 1, 2, 3};
	int arr2[5] = { 2, 3, 4 };
	TypeCopy(a1, a2, 3);
	TypeCopy(arr1,arr2,3);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值