作者WangDaMing (王大明)
看板C_and_CPP
標題[問題] decltype疑問
時間Sat Mar 27 23:36:36 2021
開發平台(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
→ nh60211as: ptr的型別是int*,defrence之後變int&吧。b[0]同理 03/27 23:52
→ nh60211as: 錯字dereference 03/27 23:53
推 jcaosola: 漲姿勢 03/28 00:38
推 KanzakiHAria: 如果你想要得到int的話用auto 03/28 12:13
→ KanzakiHAria: decltype特色就是能導出reference型態 03/28 12:13
→ KanzakiHAria: 如果要強制指定成reference則用auto & 03/28 12:14
→ KanzakiHAria: 推薦看modern effective c++ 03/28 12:14
推 g0010726: 簡單說 decltype(var) 跟 decltype (expr) 規則不同 03/28 15:49
→ g0010726: 詳細規則可以翻 cppreference 03/28 15:50
→ g0010726: 你的前兩個例子是屬於 expression, 這個狀況下 03/28 15:51
→ g0010726: lvalue expression會產生reference 03/28 15:51
→ g0010726: 第三個是 variable, 產生的type就是原本宣告的type 03/28 15:52