常量整数变量和数字的不同类型推导

Different type deduction for a const int variable and a number

本文关键字:同类型 数字 整数 变量 常量      更新时间:2023-10-16
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&"类型呢?这种类型扣除规则背后的原理是什么?

毕竟,我们可以完美地将一个数字绑定到常量左值引用。

这是因为0的类型是int,而不是const int。(标量类型没有符合 cv 标准的 prvalue。由于推导仅考虑类型,而不考虑值类别,因此T必须在此处推导为int,就像在x--- 的情况下一样,即使这会导致尝试执行无效的引用绑定。

(转发引用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.