常量整数变量和数字的不同类型推导
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&"类型呢?这种类型扣除规则背后的原理是什么?
毕竟,我们可以完美地将一个数字绑定到常量左值引用。
这是因为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.
相关文章:
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 你能在 c++ 中将不同的数字类型加在一起吗?
- 输出一个数字,该数字可能是三种类型之一
- 如何用不同的参数类型和数字回调函数
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- typeid.name 返回派生类类型之前的数字
- C++小数点后有 200 位数字的类型?
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 常量整数变量和数字的不同类型推导
- 检测<T>某些非数字类型 T 的 std::numeric::type 的特化
- 随机数字双重类型
- CRTP 模式 但是在数据结构中存储非同构类型
- 当数字可能超出C++中特定数据类型的范围时如何处理异常?
- 为什么数字类型只有"to_string()"?
- 如何在数字大于类型 size_t 的最大数量时使用 std::bitset
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- 无符号窄字符类型数字表示
- c++中对包含双精度类型数字的数组进行排序的最快方法是什么?