C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 擴展 ( expand)
擴展一個包就是將它分解為構成的元素, 對每個元素應用模式, 獲得擴展后的列表。
通過在模式右邊放一個省略號(…)來觸發(fā)擴展操作。當擴展一個包時,我們還要提供用于每個擴展元素的模式(pattern)。
eg. print 函數包含兩個擴展
// 擴展 Args template<typename T, typename...Args> ostream &print(ostream &os, const T const Args&... rest) {os ? t ? ", ";// 打印第一個實參return print(os, rest...); // 擴展rest }對 Args 的擴展中, 編譯器將模式 const Arg&應用到模板參數包 Args 中的每個元素。 因此, 此模式的擴展結果是一個逗號分隔的零個或多個類型的列表, 每個類型都形如const types&。
print (cout, i, s, 42); // 包中有兩個參數 <=> print (ostream&, const int&, const strings, const int&)//擴展即是:print (os, s, 42);2. 理解包擴展
支持更復雜的擴展模式
eg. print 調用使用了模式 debug_reg(rest),對函數參數包 rest 中的每個元素調用 debug_rep。擴展結果將是一個逗號分隔的 debug_rep 調用列表。
// 在 print 調用中對每個實參調用 debug_rep template <typename... Args> ostream &errorMsg (ostream &os, const Args &... rest) {//print (os, debug_rep (al), debug_rep (a2 ), ..., debug_rep (an)return print (os, debug_rep(rest)...); }2.1 對的代碼
errorMsg (cerr, fcnName, code.num(), otherData, "other", item); <=> print (cerr, debug_rep(fcnName), debug_rep(code.num()), debug_rep(otherData), debug_rep ("otherData"), debug_rep(item));2.2 錯的代碼
debug_rep函數不是可變參數。
//將包傳遞給 debug_rep; print(os, debug_rep(al, a2, ...an) print (os, debug_rep (rest...)); //錯誤:此調用無匹配函數 <=> print (cerr, debug_rep(fcnName, code.num(), otherData, "otherData", item));總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha