我正在阅读有关完美转发的内容,这是我了解到的让我感到困惑的事情:
当你试图实现完美转发时,你会做这样的事情:
template<class T> // If I were to call foo with an l-value int, foo would look
void foo(T &&x); // like this: void foo(int& &&x)
然后我想,等等,这是否意味着如果我这样做:
template<class T> // If I were to call foo with an l-value int, foo would look
void foo(T x); // like this: void foo(int& x);
但事实并非如此。 foo 看起来像这样:void foo(int x);
我的问题:为什么在完美的转发函数中,T变成了T&或T&&,而在另一个函数中,T不是引用?有人可以告诉我具体的规则吗?我需要一些说明!
最佳答案
模板参数T
如果它出现在 T&&
形式的函数参数中,则可以推导为引用类型仅
表单的函数模板:
template<class T> void f(T x)
- 将推导出
T
作为对象类型(x
是对象类型,因此按值传递)template<class T> void f(T& x)
- 将推导出
T
作为对象类型(然后x
具有左值引用类型)template<class T> void f(T&& x)
- 将推导出
T
作为- 或者一个左值引用(因此
x
由于引用折叠规则而具有左值引用类型) - 或作为对象类型(因此
x
具有右值引用类型)
How come in the perfect forwarding function, T turns into a T& or T&&, [...]
这是错误的。 T
成为引用类型L&
或 对象类型 R
,不是引用R&&
.
T&&
形式的函数参数于是就变成了
- 或者
L&
(因为对左值引用添加右值引用仍然是左值引用,就像add_rvalue_reference<L&>::type
仍然是L&
) - 或者变成
R&&
(因为add_rvalue_reference<R>::type
是R&&
)
关于c++ - 当你完美转发时,typename T 变成 T& 或 T&&,但当你不这样做时,T 根本不是引用。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16192796/