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; };
通过模板的特化实现 简单的类型萃取 实现memcppy时候对于特殊类型如string类的拷贝。
精选 原创
©著作权归作者所有:来自51CTO博客作者性感的玉米的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
简单的String类实现及写时拷贝
string类中深浅拷贝问题
类 string -
类型萃取
类型萃取,return,字符串,false,程序,空间
字符串 return false -
模板的特化
模板的特化
C++ 语言 模板特化