![](/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.