在C++中咱们能够经过typeid来获取一个类型的名称(内置类型和自定义类型均可以),可是咱们不能用这种方式获取来的名称作变量的声明。那么在C++中怎样识别对象的类型呢??咱们能够经过类型萃取的方式来区份内置类型和自定义类型。ide
例如:咱们在Seqlist中要用到类型萃取,由于内置类型咱们能够经过memcopy和memmove这两个方式进行拷贝,自定义类型或string咱们要经过赋值的方式拷贝。这样的话会提升效率。对象
类型萃取的方式:类型萃取是在模板的基础上区份内置类型和其余类型,主要原理是将内置类型所有特化,而后再进行区分。string
struct TrueType { bool Get() { return true; } }; struct FalseType { bool Get() { return false; } }; template<typename T> struct TypeTraits { typedef FalseType IsPODType; //若是不是内置类型,则IsPODType是FalseType }; //将全部内置类型特化 template<> struct TypeTraits<int> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<unsigned int> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<short> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<unsigned short> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<char> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<unsigned char> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<float> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<double> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<long> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<long double> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<unsigned long> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<long long> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; template<> struct TypeTraits<unsigned long long> { typedef TrueType IsPODType; //若是是内置类型则IsPODType是TrueType }; 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]; } } }