日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展

發(fā)布時間:2025/3/21 c/c++ 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. 擴(kuò)展 ( expand)

擴(kuò)展一個包就是將它分解為構(gòu)成的元素, 對每個元素應(yīng)用模式, 獲得擴(kuò)展后的列表。

通過在模式右邊放一個省略號(…)來觸發(fā)擴(kuò)展操作。當(dāng)擴(kuò)展一個包時,我們還要提供用于每個擴(kuò)展元素的模式(pattern)。

eg. print 函數(shù)包含兩個擴(kuò)展

// 擴(kuò)展 Args template<typename T, typename...Args> ostream &print(ostream &os, const T const Args&... rest) {os ? t ? ", ";// 打印第一個實(shí)參return print(os, rest...); // 擴(kuò)展rest }

對 Args 的擴(kuò)展中, 編譯器將模式 const Arg&應(yīng)用到模板參數(shù)包 Args 中的每個元素。 因此, 此模式的擴(kuò)展結(jié)果是一個逗號分隔的零個或多個類型的列表, 每個類型都形如const types&。

print (cout, i, s, 42); // 包中有兩個參數(shù) <=> print (ostream&, const int&, const strings, const int&)//擴(kuò)展即是:print (os, s, 42);

2. 理解包擴(kuò)展

支持更復(fù)雜的擴(kuò)展模式

eg. print 調(diào)用使用了模式 debug_reg(rest),對函數(shù)參數(shù)包 rest 中的每個元素調(diào)用 debug_rep。擴(kuò)展結(jié)果將是一個逗號分隔的 debug_rep 調(diào)用列表。

// 在 print 調(diào)用中對每個實(shí)參調(diào)用 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函數(shù)不是可變參數(shù)。

//將包傳遞給 debug_rep; print(os, debug_rep(al, a2, ...an) print (os, debug_rep (rest...)); //錯誤:此調(diào)用無匹配函數(shù) <=> print (cerr, debug_rep(fcnName, code.num(), otherData, "otherData", item));

總結(jié)

以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 16 模板和泛型编程)包扩展的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。