類型萃取

   在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];
              }
       }
}
相關文章
相關標籤/搜索