本周主要講的了一些比較智能化的泛型編程方法
- 萬(wàn)用的hash function
對(duì)于每個(gè)hashtable來(lái)說(shuō)昏鹃,都要將放進(jìn)來(lái)的變量或者對(duì)象給定一個(gè)唯一的編號(hào),從而確定這個(gè)變量或?qū)ο髴?yīng)該放到hashtable的哪個(gè)籃子里帽揪。因此灶伊,標(biāo)準(zhǔn)庫(kù)里面對(duì)于如何編號(hào)這件事,也就是hash code是有自己的一套方法的戏挡。而且是萬(wàn)用的货徙,特別是自C++ 2.0以來(lái)左权,因?yàn)檫\(yùn)用了Variadic templates之后。
template<typename... Types>
inline size_t hash_val(const Types&... args){
size_t seed = 0;
hash_val(seed, args...);
return seed;
}
template<typename T, typename... Types>
inline void hash_val(size_t& seed, const T& val, const Type&... args){
hash_combine(seed, val);
hash_val(seed, args...);
}
#include<functional>
template<typename T>
inline void hash_combine(size_t& seed, const T& val){
seed = std::hash<T>(val) + 0x9e3779b9
+ (seed << 6) + (seed >> 2);
}
//auxiliary generic funtions
template<typename T>
inline void hash_val(size_t& seed, const T& val){
hash_combine(seed, val);
}
-
Tuple用例
tuple事實(shí)上痴颊,就是數(shù)之組合赏迟,或元之組合。
tuple在C++ 11中的實(shí)現(xiàn)也非常優(yōu)美蠢棱,在下面的圖中锌杀。同樣通過Variadic templates,將傳給tuple類的參數(shù)一次一次的遞歸泻仙,每次的遞歸糕再,就會(huì)使當(dāng)前的tuple內(nèi)部繼承一個(gè)tuple,這樣知道最后參數(shù)全部遞歸出去玉转,剩下〇個(gè)參數(shù)的時(shí)候突想,最后就繼承一個(gè)空的tuple類。
tuple的實(shí)現(xiàn) Type Traits
type traits(類型萃取機(jī))能有效地分辨類是否具有某種類型究抓,通過調(diào)用它我們可以實(shí)現(xiàn)對(duì)不同的類型指定不同的操作猾担。下面是它的實(shí)現(xiàn)Type Traits實(shí)現(xiàn)
struct __true_type{};
struct __false_type{};
//泛化
template<class type>
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<int>{
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<double>{
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事實(shí)上绑嘹,我還沒有來(lái)得及仔細(xì)消化,就先把圖放上來(lái)吧橘茉。
-
cout
cout類
cout類 -
movable元素對(duì)于deque速度效能的影響
movable class
movable class 2 -
測(cè)試函數(shù)
測(cè)試函數(shù)