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