簡體   English   中英

const int變量和數字的不同類型推導

[英]Different type deduction for a const int variable and a number

template<typename T>
void func(T&);

int x=0;
func(x); // OK, int&

const int cx=0;
func(cx); // OK, const int&

func(0); // invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'

但是為什么在第三種情況下不能推導出'const int&'類型呢? 這種類型扣除規則背后的原理是什么?

畢竟,我們可以完美地將數字綁定到const lvalue引用。

這是因為0的類型是int ,而不是const int (沒有標量類型的cv限定的prvalue。)由於推導僅考慮類型,而不考慮值類別,因此必須像在x ---情況下那樣推導Tint即使導致嘗試執行無效的引用綁定。

轉發引用 T&&具有特殊的規則,在推導T時會考慮參數的值類別。因此,傳遞x和傳遞0會得出T不同推論。但是對於普通引用T& ,只有參數的類型很重要。)

如果您理解引用只是一個語法指針,那么我會更容易想象這里出了什么問題。 因此,如果您的方法是:

template<typename T>
void func(T*);

int x=0;
func(&x); // OK, you can take the address of x

const int cx=0;
func(&cx); // OK, you can take the address of cx

func(&0); // Taking the address of 0 doesn't make sense.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM