c 11 型別推導

2021-10-19 14:32:35 字數 3782 閱讀 7883

auto與decltype都是在編譯時期進行自動型別的推導

auto name = value;
1.

int x =0;

2.auto

*p1 =

&x;//p1 為 int *,auto 推導為 int

3.auto p2 =

&x;//p2 為 int*,auto 推導為 int*

4.auto

&r1 = x;

//r1 為 int&,auto 推導為 int

5.auto r2 = r1;

//r2 為 int,auto 推導為 int

1.

int x =0;

2.const

auto n = x;

//n 為 const int ,auto 被推導為 int

3.auto f = n;

//f 為 const int,auto 被推導為 int(const 屬性被拋棄)

4.const

auto

&r1 = x;

//r1 為 const int& 型別,auto 被推導為 int

5.auto

&r2 = r1;

//r1 為 const int& 型別,auto 被推導為 const int 型別

總結:auto與const結合的用法

template

<

typename

t>

classa;

intmain()

#

include

using

namespace std;

intmain()

#

include

using

namespace std;

classa}

;classb}

;template

<

typename

t>

void

func

(void

)int

main

(void

)

int n =20;

auto

*p =

&n, m =

99;

當型別不為引用時,auto 的推導結果將不保留表示式的 const 屬性;

當型別為引用時,auto 的推導結果將保留表示式的 const 屬性。

decltype 是「declare type」的縮寫,譯為「宣告型別」。

decltype

(exp) varname = value;

decltype

(exp) varname;

其中,varname 表示變數名,value 表示賦給變數的值,exp 表示乙個表示式。

原則上講,exp 就是乙個普通的表示式,它可以是任意複雜的形式,但是我們必須要保證 exp 的結果是有型別的,不能是 void;例如,當 exp 呼叫乙個返回值型別為 void 的函式時,exp 的結果也是 void 型別,此時就會導致編譯錯誤。

#

include

using

namespace std;

class

student

;int student::total =0;

intmain()

//函式宣告

int&

func_int_r

(int

,char);

//返回值為 int&

int&&

func_int_rr

(void);

//返回值為 int&&

intfunc_int

(double);

//返回值為 int

const

int&

fun_cint_r

(int

,int

,int);

//返回值為 const int&

const

int&&

func_cint_rr

(void);

//返回值為 const int&&

//decltype型別推導

int n =

100;

decltype

(func_int_r

(100

,'a'

)) a = n;

//a 的型別為 int&

decltype

(func_int_rr()

) b =0;

//b 的型別為 int&&

decltype

(func_int

(10.5

)) c =0;

//c 的型別為 int

decltype

(fun_cint_r(1

,2,3

)) x = n;

//x 的型別為 const int &

decltype

(func_cint_rr()

) y =0;

// y 的型別為 const int&&

using

namespace std;

class

base

;int

main()

auto 只能用於類的靜態成員,不能用於類的非靜態成員(普通成員),如果我們想推導非靜態成員的型別,這個時候就必須使用 decltype 了

#

include

using

namespace std;

template

<

typename

t>

class

base

private

:typename

t::iterator m_it;

//注意這裡};

intmain()

單獨看 base 類中 m_it 成員的定義,很難看出會有什麼錯誤,但在使用 base 類的時候,如果傳入乙個 const 型別的容器,編譯器馬上就會彈出一大堆錯誤資訊。原因就在於,t::iterator並不能包括所有的迭代器型別,當 t 是乙個 const 容器時,應當使用 const_iterator。

解決這個問題後的版本:

template

<

typename

t>

class

base

private

:decltype(t

().begin()

) m_it;

//注意這裡

};

[cv 限定符」是 const 和 volatile 關鍵字的統稱:

在推導變數型別時,auto 和 decltype 對 cv 限制符的處理是不一樣的。decltype 會保留 cv 限定符,而 auto 有可能會去掉 cv 限定符。

以下是 auto 關鍵字對 cv 限定符的推導規則:

C 11 型別推導auto

在c 11之前,auto關鍵字用來指定儲存期。在新標準中,它的功能變為型別推斷。auto現在成了乙個型別的佔位符,通知編譯器去根據初始化 推斷所宣告變數的真實型別。使用auto會拖慢c 效率嗎?完全不會,因為在編譯階段編譯器已經幫程式設計師推導好了變數的型別。使用auto會拖累c 編譯效率嗎?完全不...

C 11 型別推導auto關鍵字

在c 11中,auto關鍵字被作為型別自動型別推導關鍵字 1 基本用法 c 98 型別 變數名 初值 int i 10 c 11 auto 變數名 初值 auto i 3.14 借助於auto關鍵字,可對變數進行隱式的型別定義,即由編譯器在編譯期間根據變數的初始化語句,自動推斷出該變數的型別.aut...

c 11 型別推斷

當編譯器能夠在乙個變數的宣告時候就推斷出它的型別,那麼你就能夠用auto關鍵字來作為他們的型別 cpp view plain copy auto x 1 編譯器當然知道x是integer型別的。所以你就不用int了。接觸過泛型程式設計或者api程式設計的人大概可以猜出自動型別推斷是做什麼用的了 幫你...