在C++中,我们可以通过typeid来获取一个类型的名称,但是不能拿来做变量的声明。在C++中,我们可以通过类型萃取的方式来对内置类型和普通类型进行区分。例如将要看到的例子,如果是内置类型,string类存在浅拷贝的问题,所以必须采用值拷贝,若不是内置类型,则可调用memove拷贝函数来进行拷贝。
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];
}
}
}