CGI 萃取技術 type

2022-03-20 04:57:51 字數 2334 閱讀 9810

在原始碼中 __type_traits 在 type_traits.h 檔案定義,以下是泛化版本:

struct

__true_type ;

struct

__false_type ;

//泛化版本

template

struct

__type_traits ;

__true_type 和 __false_type 沒有任何成員,不會帶來額外負擔,卻又能標示真假。用 bool 也能達到目的,但是 bool 變數不能達到編譯期繫結。cgi 把所有內嵌型別都定義為 __false_type,即定義出最保守的值。原始碼也針對普通型別設計特化版本,具體如下:

__stl_template_null struct __type_traits;

__stl_template_null

struct __type_traitschar>;

__stl_template_null

struct __type_traitschar>;

__stl_template_null

struct __type_traits;

__stl_template_null

struct __type_traitsshort>;

__stl_template_null

struct __type_traits;

__stl_template_null

struct __type_traitsint>;

__stl_template_null

struct __type_traits;

__stl_template_null

struct __type_traitslong>;

__stl_template_null

struct __type_traits;

__stl_template_null

struct __type_traits;

__stl_template_null

struct __type_traitsdouble>;

#ifdef __stl_class_partial_specialization

template

struct __type_traits;

#endif

__stl_template_null 是個巨集定義,指 template<>。普通型別的特化版本這五個屬性均為 __true_type。

__type_traits 在原始碼中的應用很多,我這裡只舉 uninitialized_fill_n 這個全域性函式來說明,原始碼定義在 stl_uninitialized.h 檔案,具體如下:

templateinline forwarditerator

__uninitialized_fill_n_aux(forwarditerator first, size n,

const t&x, __true_type)

template

forwarditerator

__uninitialized_fill_n_aux(forwarditerator first, size n,

const t&x, __false_type)

__stl_unwind(destroy(first, cur));

}template

inline forwarditerator __uninitialized_fill_n(forwarditerator first, size n,

const t& x, t1*)

template

inline forwarditerator uninitialized_fill_n(forwarditerator first, size n,

const t&x)

上面呼叫的 fill_n 在 stl_glgobase.h 檔案定義,呼叫的函式原始碼如下:

//

填充元素到半開半閉區間[first, last)

template

void fill(forwarditerator first, forwarditerator last, const t&value)

我在程式中 debug 除錯驗證過,當 t 型別為普通型別 int,函式繫結的是呼叫 fill_n的函式,而當 t 是自定義型別,函式繫結的是含有 construct 的函式。驗證了上述分析過程的正確性。

至此,我們發現,traits 真是個好東西,比 if-else 好多了,同時是在編譯期繫結的,效率更高了,好神奇的技術,stl 原始碼值得繼續學習下去!

STL學習 萃取技術 type

之前在學習stl庫中的析構工具destory 時,提到過這樣一句話,此函式設法找到元素的數值型別,進而利用 type traits 求取適當措施。一直難以理解,現在自己總結了下自己對萃取技術的理解。讓自己困惑的程式 template void destroy t pointer template v...

C 型別萃取技術

traits技術可以用來獲得乙個 型別 的相關資訊的。template class myiterator 當我們使用myiterator時,怎樣才能獲知它所指向的元素的型別呢?我們可以為這個類加入乙個內嵌型別,像這樣 template class myiterator typedef t value...

STL 04 萃取技術

萃取第一接觸是在高中的化學課中,看來學好c 還得懂化學啊,哈哈!ps 開玩笑的!首先我解釋下化學中的萃取。利用溶質在兩種互不相容的溶劑裡溶解度的不同,用一種溶劑將溶質從另一種溶劑中提取出來。比如汽油洗衣服上的油漬。感謝我的高中化學 開始c 中的萃取 先看看什麼是特化 模板特化分為兩種 全特化 偏特化...