![](/img/trans.png)
[英]Does the C++11 standard guarantee “n2 is int&” by “auto n2 = const_cast<int&>(n);”?
[英]C++11 auto type deduction from arithmetic operation on int& and long
我一定誤會了auto
c ++ 11和更高版本如何解析類型。 我有以下代碼:
void foo(int& x)
{
++x;
}
int main()
{
int i = 2;
int& ir = i;
long L = 5;
auto a = ir/L;
foo(a);
return 0;
}
這導致編譯器錯誤:
test.cpp: In function 'int main()':
test.cpp:12:10: error: invalid initialization of non-const reference
of type ‘int&’ from an rvalue of type ‘int’
foo(a);
^
test.cpp:1:6: note: initializing argument 1 of ‘void foo(int&)’
void foo(int& x)
^~~
但是,將auto
替換為int
( int a = ir/L;
)可以很好地編譯並得到預期的結果(調用foo()
之前a == 0
之后調用a == 1
)。 在玩完代碼並看到各種錯誤消息之后,我認為auto
被推導為long int&
。 定義函數void bar(int x)
和void bar(const int& x)
導致錯誤消息: call of overloaded 'bar(long int&)' is ambiguous
。
來自評論的更正:
我不明白auto x = [int&]/[int]
導致可以由非const ref傳遞的左值,而auto x = [int&]/[long]
導致的右值不能。
ir/L
的結果是long
。 對於算術運算符 ,當二進制運算符具有不同的類型時,產生的結果將是普通類型; 在int
和long
之間會很long
。
所以auto a = ir/L;
的類型, a
是long
。 它不能傳遞給foo(int&)
因為您不能將左值引用綁定到具有不同類型的非const。
另一方面,給定L
的類型為int
,則對於auto a = ir/L;
的類型, a
會int
,那么一切都很好。
關於“錯誤的右值部分”,當您將一個long
傳遞給foo(int&)
,首先編譯器將嘗試將其轉換為int
,這是一個臨時(即一個右值),並且不能綁定到左值引用非常量。
long
可以隱式轉換為int
,而臨時變量可以綁定到const的左值引用,因此將long
變量傳遞給bar(int x)
和bar(const int&)
都很好。
順便說一句:當你寫int a = ir/L;
, long
類型的結果隱式轉換為int
。 因此,您將獲得一個int
然后將其傳遞給foo(int&)
很好。
您使用過auto
的事實並不重要。
由於論據提升的規則, a
是long
類型。
由於foo
通過引用獲取參數,因此編譯會失敗,因為int&
無法綁定到long
類型(即使它們的大小相同並且具有相同的補碼表示形式)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.