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