功能
類型萃取,在STL中用到的比較多,用於判斷一個變量是否為POD類型.
簡述來說可以用來判斷出某個變量是內置類型還是自定義類型.
通過類型萃取,萃取到變量類型,對不同變量進行不同處理,可以提升程序效率.
應用場景
比如我們實現順序表,在對順序表進行擴容時,就靠重新開辟內存、拷貝對象.
拷貝對象時,就有兩種情況:一種是類型,比如int char...;還有一種是自定義類型,Data類、String類.
對於內置類型,我們可以通過memset,來進行賦值.(擴展,淺拷貝相關的類也可以通過memset賦值)
而對於自定義類型,大多數深拷貝的對象來說,我們必須通過調用賦值語句來賦值.
因此,我們通常在拷貝對象時,為了不出現錯誤,都用賦值語句來賦值.
而我們如果有一種方法/機制可以判斷POD類型或者非POD類型.
對於POD類型用memset函數,對於非POD用賦值,這樣就能提高程序的效率
實現
類型萃取,在技術層面,就是利用了模板的特化.
簡單類型萃取的實現代碼:
template<typename T> struct TypeTraits{ static bool IsPODType(){ return false; } }; //特化int template<> struct TypeTraits<int>{ static bool IsPODType(){ return true; } }; //特化unsigned int template<> struct TypeTraits<unsigned int>{ static bool IsPODType(){ return true; } }; template<> struct TypeTraits<char>{ static bool IsPODType(){ return true; } }; template<> struct TypeTraits<unsigned char>{ static bool IsPODType(){ return true; } }; template<> struct TypeTraits<short>{ static bool IsPODType(){ return true; } }; template<> struct TypeTraits<unsigned short>{ static bool IsPODType(){ return true; } }; //.....更多類型,繼續特化就好
測試代碼:
#include<iostream> template<typename T> void CheckTypeTraits(T &v){ std::cout<<v<<"是POD類型?"<<TypeTraits<T>::IsPODType()<<std::endl; } int main(){ int a = 1; char b = '2'; short c = 3; float d = 4.4; //沒有特化處理,因此返回0 CheckTypeTraits(a); CheckTypeTraits(b); CheckTypeTraits(c); CheckTypeTraits(d); return 0; }