为什么未自动推导参考模板参数
Why are reference template parameters not deduced automatically?
在下面的示例中,我直观地期望呼叫inc(iref)
使用T=int&
调用INC功能,因为这是iref
的类型。但是,当变量传递到函数时,&
似乎已删除,因此在inc(i)
和inc(iref)
的情况下导致T=int
。我期望的行为仅在明确指定模板参数为参考时才发生。
template<typename T>
void inc(T t) {
t++;
}
int main() {
int i = 41;
int& iref = i;
iref++;
std::cout << i << " " << iref << std::endl; // prints 42 42, as expected
inc(i);
std::cout << i << " " << iref << std::endl; // still prints 42 42, as expected
inc(iref);
std::cout << i << " " << iref << std::endl; // prints 42 42, instead of 43 43
inc<int&>(iref);
std::cout << i << " " << iref << std::endl; // now finally prints 43 43
}
所以,我的问题是:
- 当通过
inc(iref)
传递时,为什么参考似乎会变成"裸机"值?它背后的过程是什么? - 为什么它以这种方式工作/该设计决定背后的理由是什么?如果我按照我直觉上的期望,它会有任何问题或负面后果吗?
参考被剥离的参考值,因为如果不是IREF,则否则是模棱两可的(int&amp;或int)。它是通过这种方式设计的,因此您可以像:
那样超载它。#include <iostream>
template<typename T>
void inc(T& t) {
t++;
}
int main() {
int i = 41;
int& iref = i;
inc(iref);
std::cout << iref << std::endl;
}
相关文章:
- Lambda闭包左值可以作为右值参考参数传递
- 遍历地图并将该对用作参考参数 C++11
- 什么是常量参考参数以及如何使用它?
- 如何将rvalue作为参考参数传递给函数
- 移动 l 值参考参数是否是一种不好的做法?
- C 11:为什么RVALUE参考参数隐式转换为LVALUE
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- 如何处理可能指向内部数据的参考参数
- C 功能具有参考参数错误的迭代器错误.寻求解释
- 用emscripten中的参考参数绑定函数
- 一种体面的方式来转换const列表参考参数,然后传递到另一个函数
- 参考参数和递归
- 分配运算符过载:返回void与返回参考参数
- C ,构造器中允许的参考参数默认值
- Qt信号和插槽:是复制的参考参数
- C 接收const lvalue和rvalue参考参数,而无需过载
- std ::移动返回和输入参考参数
- 参考参数返回副本
- 如何使用数组和参考参数调用void函数
- 按值传递参考参数