通過模板的特化實現 簡單的類型萃取 實現memcppy時候對於特殊類型如string類的拷貝。

C++怎樣識別一個對象的類型?
typeid可以獲取到一個類型的名稱,但是不能拿來做變量的聲明。

【POD類型萃取】
//
// POD: plain old data 平凡類型(無關痛癢的類型)--基本類型
// 指在C++ 中與 C兼容的類型,可以按照 C 的方式處理。
//#include<iostream>
#include<string>
using namespace std;

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

template<>
struct TypeTraits<char>
{
 typedef __TrueType __IsPodType;
};

template<>
struct TypeTraits<short>
{
 typedef __TrueType __IsPodType;
};

template<class T>
struct TypeTraits<T*>
{
 typedef __TrueType __IsPodType;
};

template<class T>
struct TypeTraits<T&>
{
 typedef __TrueType __IsPodType;
};


template <class T>
void __memcpy(T* dst, T *scr, size_t _size)
{
 cout << "__TrueType" << typeid(T).name() << endl;
 if (TypeTraits<T>::__IsPodType().Get())//是基本類型
 {
  memcpy(dst, scr, _size*sizeof(T));
 }
 else
 {
  for (int i = 0; i < _size; ++i)
  {
   dst[i] = scr[i];
  }
 }
}


template<typename T>
class Seqlist
{
public:
 Seqlist() :_array(new T[_capcity]), _size(0), _capcity(0)
 {}
 void PushBack(const T& x)
 {
  update();
  _array[_size++] = x;

 }
 void update()
 {
  if (_size >= _capcity)
  {
   _capcity = _capcity * 2 + 3;
   T* tmp = new T[_capcity];
   __memcpy(tmp, _array, _size);
   delete[]_array;
   _array = tmp;
  }
 }
 //~Seqlist()
 //{
 // if (_array)
 //  delete[] _array;
 //}
 void Print()
 {
  for (int i = 0; i < _size; ++i)
  {
   cout << _array[i] << " ";
  }
  cout << endl;
 }
 public:
 size_t _size;
 size_t _capcity;
 T* _array;

};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章