模板中的类型萃取
因为C++中并不支持类型的比较,有些时候就不是很方便了,比如我们进行拷贝的时候,要考虑到不同的类型而采用不同的拷贝方法,例如之前实现的Vector中的拷贝函数,我们统一采用的是一个一个赋值的方法,并没有用memcpy直接进行拷贝,因为考虑到string类型或者其他自定义类型的更深层次的拷贝,但是我们知道内置类型是可以直接用memcpy进行拷贝的,因为这样效率更高一些,那么今天实现一下类型萃取,来优化我们的拷贝函数。
先贴上代码
#include <iostream>
#include <string>
#include <string.h>
#include <typeinfo>
#include <stdio.h>
using namespace std;
struct _false_Type//定义两个空类,只是为了后面的类型区分
{};
struct _ture_Type
{};
template<class T>
struct _Type_Traits//类型的萃取
{
typedef _false_Type _pod_Type;//将false_Type 类型重定义为_pod_Type(无关痛痒类型),表示该类型不是内置类型,下面的特化版本将处理内置类型
//当调用普通版本的时候即非特化版本
};
//**************************将内置类型都定义为特化*******************************
template<>
struct _Type_Traits<int>
{
typedef _ture_Type _pod_Type;//将_true_Type 类型重定义为_pod_Type(无关痛痒类型),表示该类型为内置类型
};
//将内置类型都定义为特化
template<>
struct _Type_Traits<char>
{
typedef _ture_Type _pod_Type;//将_true_Type 类型重定义为_pod_Type(无关痛痒类型)
};
//将内置类型都定义为特化
template<>
struct _Type_Traits<float>
{
typedef _ture_Type _pod_Type;//将_true_Type 类型重定义为_pod_Type(无关痛痒类型)
};
//将所有的内置类型都定义为特化,这里不一一举例
//**********************拷贝的实现--memcpy********************************
template<class T>
void _My_Copy(T * dst,const T * src,size_t n,_ture_Type )
{//内置类型用memcpy()
memcpy(dst,src,sizeof(T)*n);
cout<<"memcpy->"<<endl;
}
//**********************拷贝的实现--赋值**********************************
template<class T>
void _My_Copy(T * dst,const T * src,size_t n,_false_Type )//这里没有必要用形参接收
{//非内置类型用值拷贝一个一个赋值
size_t i=0;
for(i=0;i<n;++i)
{
dst[i]=src[i];
}
cout<<"operator=()->"<<endl;
}
template<class T>
void My_Copy(T * dst,const T *src,size_t n)
{
_My_Copy(dst,src,n, typename _Type_Traits<T>::_pod_Type());//根据是不是特化版本来区分是调用哪个重载的拷贝函数
//这里的第三个参数的理解见下面的图片进行解释
}
void Test_Copy()
{
const int N=5;
int arr1[N]={1,2,3,4,5};
int arr2[N]={0};
My_Copy(arr1,arr2,N);
string arr_str1[N]={"aaa","bbb","ccc","ddd","eee"};//内置类型走特化,调用用memcpy()的拷贝
string arr_str2[N]={"","","","",""};//自定义类型走普通版本,调用一个一个赋值的拷贝
My_Copy(arr_str2,arr_str1,N);
}
int main()
{
Test_Copy();
return 0;
}