简体   繁体   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'

But why doesn't the 'const int&' type get deduced in the third case? 但是为什么在第三种情况下不能推导出'const int&'类型呢? What is the rationale behind this type deduction rule? 这种类型扣除规则背后的原理是什么?

After all, we can perfectly bind a number to const lvalue reference. 毕竟,我们可以完美地将数字绑定到const lvalue引用。

It's because the type of 0 is int , not const int . 这是因为0的类型是int ,而不是const int (There are no cv-qualified prvalues of scalar type.) Since the deduction only takes into account the type, and not the value category, T must be deduced as int here just as it was in the case of x --- even though that results in an attempt to perform an invalid reference binding. (没有标量类型的cv限定的prvalue。)由于推导仅考虑类型,而不考虑值类别,因此必须像在x ---情况下那样推导Tint即使导致尝试执行无效的引用绑定。

(A forwarding reference T&& has special rules that take into account the argument's value category when deducing T . So passing in x and passing in 0 would deduce T differently. But for an ordinary reference T& , only the argument's type matters.) 转发引用 T&&具有特殊的规则,在推导T时会考虑参数的值类别。因此,传递x和传递0会得出T不同推论。但是对于普通引用T& ,只有参数的类型很重要。)

I find it easier to imagine whats going wrong here if you understand that a reference is just a pointer with syntax. 如果您理解引用只是一个语法指针,那么我会更容易想象这里出了什么问题。 So if your method was: 因此,如果您的方法是:

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