Boost庫中的Traits(is_float, is_class)

 對以判斷是不是某個基本類型(整數, 浮點, bool)可以參考下面代碼:

3. is_float

  1. template<typename T>  
  2. struct is_float : bool_type<false>{};  
  3.   
  4. #define IS_FLOAT(T)  template<> struct is_float<float> : bool_type<true>{};/  
  5.     template<> struct is_float<const float> : bool_type<true>{};/  
  6.     template<> struct is_float<volatile float> : bool_type<true>{};/  
  7.     template<> struct is_float<const volatile float> : bool_type<true>{}  
  8.   
  9. IS_FLOAT(float);  
  10. IS_FLOAT(double);  
  11. IS_FLOAT(long double);  

 

4. is_calss

判斷一個類型T是不是類可以判斷是不是存在 void(T::*)(void)類型的成員函數, 當然這裏並不需要真存在。

由於對struct, class這些都是滿足的, 所以並不能吧struct和class中區分出來。

  1. typedef char yes_type;  
  2. typedef int no_type;  
  3.   
  4. template<typename T>  
  5. struct is_class_imp{  
  6.     template <typename U> static yes_type is_calss_tester(void(U::*)(void));  
  7.     template <typename U> static no_type is_calss_tester(...);  
  8.   
  9.     static const bool value = (sizeof(is_calss_tester<T>(0)) == sizeof(yes_type));  
  10. };  
  11.   
  12. template<typename T>  
  13. struct is_class : is_class_imp<T>{};  
  14.   
  15.   
  16. struct A{};  
  17. class B{};  
  18. enum C{};  
  19.   
  20. int main()  
  21. {  
  22.     bool is_1 = is_class<int>::value;  //false  
  23.     bool is_2 = is_class<A>::value;  
  24.     bool is_3 = is_class<B>::value;  
  25.     bool is_4 = is_class<C>::value;     //false  
  26.     bool is_6 = is_class<const A>::value;  
  27. }  

 

後面回接着講述

is_function

is_member_function_pointer

is_member_object_pointer

is_member_pointer

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