[問題] decltype疑問

看板C_and_CPP (C/C++)作者 (王大明)時間3年前 (2021/03/27 23:36), 3年前編輯推噓3(309)
留言12則, 4人參與, 3年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 問題(Question): #include <iostream> int main() { int a; int *ptr = &a; int b[10] = {0}; int &d = a; decltype(*ptr) c1 = a;//int & decltype(b[0]) c2 = a;//int & decltype(ptr) c3 = &a; //int * } 最近再看decltype,書上說c1,c2都是"int &" 雖然這是結果,可是其實我還是不是很懂,為何c1,c2不是"int" 有人能更好的解釋為何c1,c2不應該是int?? 還是就是規定沒什麼好說? 感謝各位 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.11.98.99 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1616859398.A.A25.html ※ 編輯: WangDaMing (39.11.98.99 臺灣), 03/27/2021 23:38:15

03/27 23:52, 3年前 , 1F
ptr的型別是int*,defrence之後變int&吧。b[0]同理
03/27 23:52, 1F

03/27 23:53, 3年前 , 2F
錯字dereference
03/27 23:53, 2F

03/28 00:38, 3年前 , 3F
漲姿勢
03/28 00:38, 3F

03/28 12:13, 3年前 , 4F
如果你想要得到int的話用auto
03/28 12:13, 4F

03/28 12:13, 3年前 , 5F
decltype特色就是能導出reference型態
03/28 12:13, 5F

03/28 12:14, 3年前 , 6F
如果要強制指定成reference則用auto &
03/28 12:14, 6F

03/28 12:14, 3年前 , 7F
推薦看modern effective c++
03/28 12:14, 7F

03/28 15:49, 3年前 , 8F
簡單說 decltype(var) 跟 decltype (expr) 規則不同
03/28 15:49, 8F

03/28 15:50, 3年前 , 9F
詳細規則可以翻 cppreference
03/28 15:50, 9F

03/28 15:51, 3年前 , 10F
你的前兩個例子是屬於 expression, 這個狀況下
03/28 15:51, 10F

03/28 15:51, 3年前 , 11F
lvalue expression會產生reference
03/28 15:51, 11F

03/28 15:52, 3年前 , 12F
第三個是 variable, 產生的type就是原本宣告的type
03/28 15:52, 12F
文章代碼(AID): #1WNr46eb (C_and_CPP)
文章代碼(AID): #1WNr46eb (C_and_CPP)