当完全转发时,类型名称T成为T&或T&& amp;& amp;&&&&&

编程入门 行业动态 更新时间:2024-10-28 12:23:32
本文介绍了当完全转发时,类型名称T成为T&或T&& amp;& amp;&&&&&& amp;怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读完美的转发,这是我学到的困惑我:当你想达到完美的转发,你会做这样的:

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)

T> void f(T& x)
将推导出 T 作为对象类型(然后 x 有lvalue引用类型)

template<class T> void f(T& x)
will deduce 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 like add_rvalue_reference<L&>::type is still L&)
  • or it becomes R&& (because add_rvalue_reference<R>::type is R&&)

更多推荐

当完全转发时,类型名称T成为T&amp;或T&amp;&amp; amp;&amp; amp;&amp;&amp

本文发布于:2023-09-23 00:00:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   类型   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!