【发布时间】:2018-01-17 15:22:59
【问题描述】:
template <typename T>
void fun1(T t) {}
template <typename T>
void fun2(T && t) {}
int i = 1;
fun1(i); // the deduced type of T is int
fun2(i); // the deduced type of T is int &
fun1(i)和fun2(i)中T的推导类型分别是int和int &,谁能解释一下编译器如何推导的机制?
更新
这个问题不是Type not deduced to be r-value reference: why not?的重复问题,因为:
后面的问题解释了以下的扣除规则:
template <class T>
void foo(T&& )
这里想了解一下扣分规则的区别
template <class T>
void foo(T&& )
和
template <class T>
void foo(T )
【问题讨论】:
-
您希望得到什么?
int和int&&都会使t成为右值引用,它不能绑定到左值i。 -
不,不是。请参阅更新。 @E_net4
-
不同之处在于它们是不同的函数签名。
fun1(T)总是按值传递,fun2(T&&)根据链接副本中解释的规则推导。它们没有其他关系。 -
我知道 fun2(i) 是通过左值引用传递的,但是为什么 fun1(i) 是通过值传递而不是左值引用呢? @thirtythreeforty
标签: c++ rvalue-reference