Re: [問題] auto用法一問

看板C_and_CPP (C/C++)作者 (Args&&... args)時間2年前 (2021/11/15 03:20), 2年前編輯推噓1(106)
留言7則, 3人參與, 2年前最新討論串3/3 (看更多)
首先第一點 auto只能推導 靜態型別 也就是編譯時期就能確定的型別 所以看到程式中有virtual這個關鍵字 用auto就要小心了 但原po這個例子沒問題 再來回到原PO的問題 Q: 你如何知道你的auto推導出來的是什麼型別? 這邊提供一個檢查技巧/範例 (effective modern c++這本書有) //先創建一個測試用的class TD template<typename T> // declaration only for TD; class TD; // TD == "Type Displayer" //以auto宣告型別並初始化 auto t = "some string"; //使用TD TD<decltype(t)> tType; //這時候你通常會看到類似的編譯錯誤訊息 error: aggregate 'TD<char*> tType' has incomplete type and cannot be defined 那個 'TD<char*> tType'裡面的char*就是你用auto推出來的型別 再看這例子 std::vector<bool> features(const Widget& w); Widget w; … auto highPriority = features(w)[5]; // is w high priority? … processWidget(w, highPriority); // process w in accord // with its priority 你猜highPriority會被推成什麼型別? 理想的bool? 不對 它被推成 std::vector<bool>::reference 這個型別 這關係到std::vector<bool>裡面的實作方式 這時候只能避開auto了 乖乖使用bool 但可以用上面的方式先檢查推導出來的型別 (後面一點的compiler 好像可以正常推導出bool) 補充: 個人最推薦的auto使用情境 template<typename It> // algorithm to dwim ("do what I mean") void dwim(It b, It e) // for all elements in range from { //想自動取得It<T> 裡面的型別T作為初始化宣告 T val = ... } 你有想過我要如何自動得到並初始化 It<T>裡面的型別T嗎? 答案是要用到trait-class (沒用auto的話) template<typename It> // algorithm to dwim ("do what I mean") void dwim(It b, It e) // for all elements in range from { // b to e while (b != e) { typename std::iterator_traits<It>::value_type currValue = *b; … } } 三小? 這麼簡地的事情 也要弄到那麼複雜的trait-class? C++11自從有了auto之後, 這件事情不再痛苦 這件事情不再痛苦 template<typename It> // as before void dwim(It b, It e) { while (b != e) { auto currValue = *b; … } 參考: Effective Modern C++ item5 與 item6 <大推這本書> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.24.242.118 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1636917646.A.863.html ※ 編輯: dzwei (114.24.242.118 臺灣), 11/15/2021 04:17:50

11/16 10:37, 2年前 , 1F
可惜作者已經...
11/16 10:37, 1F

11/16 11:49, 2年前 , 2F
作者怎麼了owo
11/16 11:49, 2F

11/16 11:57, 2年前 , 3F
在2015年宣布退出C++世界... QQ
11/16 11:57, 3F

11/16 22:04, 2年前 , 4F
剛查了~還真退了!本來在等他講c++20 XD
11/16 22:04, 4F

11/17 08:17, 2年前 , 5F
宣布退出的時候本來還說會對已出版的書持續勘誤
11/17 08:17, 5F

11/17 08:20, 2年前 , 6F
但在2018時大師發現自己已經無法對讀者寄來的TR進行確認
11/17 08:20, 6F

11/17 08:21, 2年前 , 7F
所以現在連勘誤都...
11/17 08:21, 7F
文章代碼(AID): #1XaM6EXZ (C_and_CPP)
文章代碼(AID): #1XaM6EXZ (C_and_CPP)