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