C auto和decltype型別說明符

2021-09-27 08:10:11 字數 1617 閱讀 9207

c++ auto和decltype型別說明符

有時候我們定義帶初始值的變數時,不知道或難以確定表示式的型別,我們可以用auto或decltype型別說明符,讓編譯器根據表示式自動推斷變數的型別。例如,我們不知道或難以確定val1和val2的型別,或者不知道它有沒有重新定義加法,使得結果型別改變,我們可以這樣:

auto item = val1 + val2;

//item的型別由編譯器確定,編譯器根據val1和val2相加的結果確定型別。

想要用好auto和decltype的便利,就要弄清楚編譯器是怎麼自動推斷型別的,有哪些注意事項:

//當引用被作為auto變數初始值時,編譯器將auto推斷為所引用物件的型別。

int i =0;

int&r = i;

auto a = r;

// a的型別為int

//auto 一般忽略頂層(top-level)const,保留底層(low-level)const

const

int ci = i;

const

int&cr = ci;

auto b = ci;

// 相當於 "int b = ci;" (忽略了top-level const)

auto c = cr;

// 相當於"int c = cr;"

auto d =

&i;// 相當於"int *d = &i;"

auto e =

&ci;

// 相當於"const int *e = &ci;",e的值可修改,但所指向內容為const的不可修改(保留了low-level const)

//auto 用於引用時不忽略頂層(top-level)const

auto

&rf = ci;

// 相當於"const int &rf = ci;",其實rf是ci別名,如果忽略了const的話,也講不通

//decltype處理頂層const和引用的方式與auto不同

decltype

(ci) x =0;

// 相當於 const int x = 0;

decltype

(cr) y = x;

// 相當於 const int &y = x;

//如果decltype括號裡是表示式,那麼返回表示式結果對應的型別

int i =42;

int*p =

&i;int

&r = i;

decltype

(r) b = i;

// 相當於 int &b = i; r是個引用

decltype

(r+0

) c = i;

// 相當於 int c = i; r與0相加結果是個具體值,不是引用

decltype

(*p) d = i;

// 相當於 int &d = i; 由於*是解引用,所以*p是乙個引用型別

note:

for

(auto item : v)

《c++ prime 第五版》p61

《c++ prime 第五版》p62

c auto和decltype關鍵字

可以用 auto 關鍵字定義變數,編譯器會自動判斷變數的型別。例如 auto i 100 i 是 int auto p new a p 是 a auto k 34343ll k 是 long long 有時,變數的型別名特別長,使用 auto 就會很方便。例如 map mp for auto i m...

C auto和decltype關鍵字

可以用 auto 關鍵字定義變數,編譯器會自動判斷變數的型別。例如 auto i 100 i 是 int auto p newa p 是 a auto k 34343ll k 是 long long有時,變數的型別名特別長,使用 auto 就會很方便。例如 map int,greater mp fo...

auto 和 decltype的區別

auto和decltype都是型別推斷的兩種方式,但之間又有區別。主要有這幾個方面的區別 1.auto是通過編譯器計算變數的初始值來推斷型別的,decltype同樣也是通過編譯器來分析表示式進而得到它的型別,但是它不用將表示式的值計算出來。2.編譯器推斷出來的auto型別有可能和初始值型別不同,比如...