C decltype型別說明符

2022-05-15 04:48:20 字數 2461 閱讀 7556

decltype

語法為:

decltype( expression )

編譯器使用下列規則來確定expression

int

var;

const

int&&fx();

struct a

const a* a = new a();

語句型別

注釋decltype(fx());

const int &&

對左值引用的const int

decltype(var);

int

decltype(a->x);

double

成員訪問的型別

decltype((a->x));

const double&

//

decltype的結果可以是引用型別

int i = 42, *p = &i, &r =i;

decltype(r + 0) b; //

ok, 加法的結果是int,因此b是乙個(未初始化)的int

decltype(*p) c; //

error, c是int&, 必須初始化

因為r是乙個引用,因此decltype(r)的結果是引用型別,如果想讓結果型別是r所指的型別,可以把r作為表示式的一部分,如r+0,顯然這個表示式的結果將是乙個具體的值而非乙個引用。

另一方面,如果表示式的內容是解引用操作,則decltype將得到引用型別。正如我們所熟悉的那樣,解引用指標可以得到指標所指物件,而且還能給這個物件賦值,因此,decltype(*p)的結果型別是int&而非int

如果decltype使用的表示式是乙個變數,則decltype返回該變數的型別(包括頂層const和引用在內):

const

int ci = 0, &cj =ci;

decltype(ci) x = 0; //

x的型別是const int

decltype(cj) y = x; //

y的型別是const int&,y繫結到變數x

decltype(cj) z; //

error, z是乙個引用,必須初始化

對於decltype所用的引用來說,如果變數名加上了一對括號,則得到的型別與不加括號時會有所不同。如果decltype使用的是乙個不加括號的變數,則得到的結果就是該變數的型別;如果給變數加上了一層或多層括號,編譯器就會把它當成是乙個表示式。

decltype((i)) d; //

error, d是int&, 必須初始化

decltype(i) e; //

ok, e是乙個未初始化的int

//

c++11

templateauto myfunc(t&& t, u&& u) -> decltype (forward(t) + forward(u))

;//c++14

templatedecltype(auto) myfunc(t&& t, u&&u)

;

forward:如果引數是右值或右值引用,則有條件地將其引數強制轉換為右值引用。)

#include #include 

#include

#include

using

namespace

std;

template

auto plus(t1&& t1, t2&& t2) ->decltype(forward

(t1) + forward(t2))

class

xpublic

: x(

intdata) : m_data(data) {}

int dump() const

private

:

intm_data;

};int

main()

執行結果為:

plus(i, 9) = 13

plus(dx, dy) = 13.5

hello, world!x3.dump() = 42

C decltype型別說明符

decltype 語法為 decltype expression 編譯器使用下列規則來確定expression int var const int fx struct a const a a new a 語句型別注釋 decltype fx const int 對左值引用的const int dec...

auto型別說明符

c 11新標準引入了auto型別說明符 用它能讓編譯器替我們分析表示式所屬的型別 auto讓編譯器通過初始值來推算出標量的型別。顯然auto定義的變數必須有初始值 auto item vall val2 item的型別通過val2和val1的相加的結果得出 使用auto也能在一條語句中宣告多個變數 ...

auto型別說明符

程式設計時,需要把表示式的值賦給變數,這就要求在宣告變數時清楚知道表示式的型別。為了解決這個問題,c 11引入auto型別說明符,用它就能讓編譯器替我們去分析表示式所屬的型別。auto讓編譯器通過初值來推算變數的型別。因此,auto定義的變數必須有初始值。auto能在一句中定義多個變數,但是這幾個變...