C++之类型萃取技巧
?
使用類型萃取的原因
就是當(dāng)你的順序表是自定義類型,我們進(jìn)行順序表增容的時(shí)候,這個(gè)時(shí)候會(huì)出現(xiàn)一個(gè)問(wèn)題,比如string類型,這個(gè)類型中有一個(gè)_buf與_ptr,當(dāng)儲(chǔ)存少于16個(gè)的時(shí)候這時(shí)會(huì)儲(chǔ)存在_buf當(dāng)中的,如果多于16個(gè),那個(gè)會(huì)單獨(dú)開(kāi)辟空間,進(jìn)行儲(chǔ)存,這時(shí)拷貝的時(shí)候就是拷貝過(guò)去這個(gè)儲(chǔ)存的地址而已,所以這樣調(diào)用析構(gòu)函數(shù)的時(shí)候,當(dāng)增加容量的時(shí)候,這個(gè)時(shí)候會(huì)把儲(chǔ)存string的那塊空間進(jìn)行釋放。會(huì)造成數(shù)據(jù)丟失的問(wèn)題。
?
所以,在這里面我們提到一個(gè)類型萃取的技巧,可以把自定義類型和內(nèi)置類型的區(qū)分開(kāi),然后對(duì)自定義類型的使用for循環(huán)拷貝,對(duì)于內(nèi)置類型的,采用memcpy的方式進(jìn)行拷貝
#include<iostream> #include<stdlib.h>using namespace std;//類型萃取 struct __truetype {bool get(){return true;} };struct __falsetype {bool get(){return false;}};template<typename 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<> struct typetraits<bool > {typedef __truetype __ispodtype; }; template<> struct typetraits<unsigned int > {typedef __truetype __ispodtype; }; template<> struct typetraits<unsigned short > {typedef __truetype __ispodtype; }; template<> struct typetraits<unsigned long > {typedef __truetype __ispodtype; }; template<> struct typetraits<long > {typedef __truetype __ispodtype; }; template<> struct typetraits<long long > {typedef __truetype __ispodtype; }; template<> struct typetraits<unsigned long long > {typedef __truetype __ispodtype; };template<> struct typetraits<long double > {typedef __truetype __ispodtype; }; template<> struct typetraits<double > {typedef __truetype __ispodtype; };template<> struct typetraits<float > {typedef __truetype __ispodtype; };template<typename T> void Copy(const T*src, T* dst, size_t size) {if (typetraits<T>::__ispodtype().get()){cout << "__truetype:" << typeid(T).name() << endl;memcpy(dst, src, size*sizeof(T));}else{cout << "__falsetype:" << typeid(T).name() << endl;for (size_t i = 0; i < size; i++){dst[i] = src[i];}}}void test() {int a1[8] = { 1, 2, 3, 4, 5, 6 };int a2[8] = { 9, 5, 6, 7, 8, 2, 2 };Copy(a1, a2, 3);cout << a2<<endl;string c1[10] = {"123","7989465","456321","4561","4563"};string c2[5] = {"654","312","a"};Copy(c1, c2, 3);} int main() {test();system("pause");return 0; }在這里我們采用了模板的特化,這里使用了全特化,直接給int,double等內(nèi)置類型做特化。
在這里我們?cè)O(shè)定內(nèi)置類型是truetype,設(shè)置自定義類型是falsetype,然后我們通過(guò)不同的類型利用get()函數(shù)返回不同的布爾值,這樣對(duì)內(nèi)置類型采用memcp拷貝,對(duì)于非內(nèi)置類型,采用for循環(huán)拷貝,這樣就能實(shí)現(xiàn)我們想要的結(jié)果了。
?
總結(jié)
以上是生活随笔為你收集整理的C++之类型萃取技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++模板的那丢丢事儿
- 下一篇: 机器学习实战教程(四):朴素贝叶斯基础篇