[英]C++ : Different deduction of type auto between const int * and cont 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
---情况下那样推导T
为int
, 即使导致尝试执行无效的引用绑定。
( 转发引用 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.