为什么要用到类型萃取?
在C++中,想要对数据进行拷贝的话,通常有两种情况
- 内置类型
- 自定义类型
对于内置类型,我们可以使用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];
}
}
}