lxidea的 Boolan STL与泛型编程 学习笔记(五)

本周主要讲的了一些比较智能化的泛型编程方法

  1. 万用的hash function
    对于每个hashtable来说,都要将放进来的变量或者对象给定一个唯一的编号,从而确定这个变量或对象应该放到hashtable的哪个篮子里。因此,标准库里面对于如何编号这件事,也就是hash code是有自己的一套方法的。而且是万用的,特别是自C++ 2.0以来,因为运用了Variadic templates之后。
template  
inline size_t hash_val(const Types&... args){  
      size_t seed = 0;  
      hash_val(seed, args...);  
      return seed;  
}  
  
template  
inline void hash_val(size_t& seed, const T& val, const Type&... args){  
      hash_combine(seed, val);  
      hash_val(seed, args...);  
}  

#include  
template  
inline void hash_combine(size_t& seed, const T& val){  
        seed = std::hash(val) + 0x9e3779b9  
              + (seed << 6) + (seed >> 2);  
}  
//auxiliary generic funtions  
template  
inline void hash_val(size_t& seed, const T& val){  
      hash_combine(seed, val);  
}  
  1. Tuple用例
    tuple事实上,就是数之组合,或元之组合。
    tuple在C++ 11中的实现也非常优美,在下面的图中。同样通过Variadic templates,将传给tuple类的参数一次一次的递归,每次的递归,就会使当前的tuple内部继承一个tuple,这样知道最后参数全部递归出去,剩下〇个参数的时候,最后就继承一个空的tuple类。


    tuple的实现
  2. Type Traits
    type traits(类型萃取机)能有效地分辨类是否具有某种类型,通过调用它我们可以实现对不同的类型指定不同的操作。下面是它的实现

  3. Type Traits实现

struct __true_type{};  
struct __false_type{};  
//泛化  
template  
struct __type_traits{  
      typedef __true_type this_dummy_member_must_be_first;  
      typedef __false_type has_trivial_default_constructor;  
      typedef __false_type has_trivial_copy_constructor;  
      typedef __false_type has_trivial_assignment_operator;  
      typedef __false_type has_trivial_destructor;  
      typedef __false_type is_POD_type;  //POD = Plain Old Data,代表旧式的class 也就是struct  
};  
  
//int的特化  
template<>   
struct __type_traits{  
      typedef __true_type has_trivial_default_constructor;  
      typedef __true_type has_trivial_copy_constructor;  
      typedef __true_type has_trivial_assignment_operator;  
      typedef __true_type has_trivial_destructor;  
      typedef __true_type is_POD_type;  
}  
  
//double的特化  
template<>   
struct __type_traits{  
      typedef __true_type has_trivial_default_constructor;  
      typedef __true_type has_trivial_copy_constructor;  
      typedef __true_type has_trivial_assignment_operator;  
      typedef __true_type has_trivial_destructor;  
      typedef __true_type is_POD_type;  
}  

第5和第6事实上,我还没有来得及仔细消化,就先把图放上来吧。

  1. cout


    cout类

    cout类
  2. movable元素对于deque速度效能的影响


    movable class

    movable class 2
  3. 测试函数


    测试函数

你可能感兴趣的:(lxidea的 Boolan STL与泛型编程 学习笔记(五))