当完全转发时,类型名称T成为T&或T&& amp;& amp;&&&&&& amp;怎么样? [英] When you perfect-forward, typename T becomes a T& or T&&, but when you don't, T isn't a reference at all. How?
问题描述
我正在阅读完美的转发,这是我学到的困惑我:
当你想达到完美的转发,你会做这样的:
I'm reading about perfect forwarding, and this is something I've learnt that has confused me:
When you're trying to achieve perfect forwarding, you'll do something like this:
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)
等待,这意味着如果我这样做:
So then I thought, wait, does that mean that if I did this:
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);
但这不是什么事情。 改为: void foo(int x);
But that's not what happens. foo instead looks like this: void foo(int x);
我的问题:如何完美的转发功能,T变成一个T&或T&& amp;& amp;&&&&&&&有人可以告诉我这个的确切规则吗?我需要一些澄清!
推荐答案
模板参数 T
如果它出现在 T&&&
A template parameter T
can be deduced as a reference type only if it appears in a function parameter of the form T&&
以下形式的函数模板:
-
;类T> void f(T x)
- 将推导出
T
作为对象类型(和/ code>是对象类型,因此通过值传递)
template<class T> void f(T x)
- will deduce
T
as an object type (andx
is an object type so is passed by value)
T> void f(T& x)
T
作为对象类型(然后 x
有lvalue引用类型)
template<class T> void f(T& x)
T
as an object type (and then x
has lvalue reference type)
template< class T& void f(T& x)
T
为
- 一个左值引用(因为引用折叠规则,所以
x
有左值引用类型) / li>
- 或作为对象类型(因此
x
具有右值引用类型)
- either an lvalue reference (so
x
has lvalue reference type due to reference collapsing rules) - or as an object type (so
x
has rvalue reference type)
进入完美的转发功能,T变成T&
How come in the perfect forwarding function, T turns into a T& or T&&, [...]
这是错误的。 T
变成参考类型 L&
或 $ c> R ,不是参考 R&&&
。
因此 T&&
的函数参数变为
This is wrong. T
becomes a reference type L&
or an object type R
, not a reference R&&
.
The function parameter of the form T&&
thus becomes
- code> L& (因为添加对左值引用的右值引用仍然是一个左值引用,就像
add_rvalue_reference< L&> :: type
仍为L&
) - 或变为
R&& $ c>(因为
add_rvalue_reference< R> :: type
是R&&&< / code>)
- either
L&
(because adding an rvalue reference to an lvalue reference is still an lvalue reference, just likeadd_rvalue_reference<L&>::type
is stillL&
) - or it becomes
R&&
(becauseadd_rvalue_reference<R>::type
isR&&
)
这篇关于当完全转发时,类型名称T成为T&或T&& amp;& amp;&&&&&& amp;怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!