我正在阅读完美的转发,这是我学到的困惑我:当你想达到完美的转发,你会做这样的:
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 (and x is an object type so is passed by value)
- 一个左值引用(因为引用折叠规则,所以 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 like add_rvalue_reference<L&>::type is still L&)
- or it becomes R&& (because add_rvalue_reference<R>::type is R&&)
更多推荐
当完全转发时,类型名称T成为T&或T&& amp;& amp;&&
发布评论