当您进行完美转发时,类型名称T变为T& amp;.或T& amp; amp; amp; amp; amp; amp; amp; amp;但当您不这样做时,T根本不是参考.如何? [英] When you perfect-forward, typename T becomes a T& or T&&, but when you don't, T isn't a reference at all. How?

查看:75
本文介绍了当您进行完美转发时,类型名称T变为T& amp;.或T& amp; amp; amp; amp; amp; amp; amp; amp;但当您不这样做时,T根本不是参考.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关完美转发的信息,这使我感到困惑:
当您尝试实现完美转发时,您将执行以下操作:

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);

但事实并非如此. foo 看起来像这样: void foo(int x);

But that's not what happens. foo instead looks like this: void foo(int x);

我的问题:完美的转发功能如何将T变成T&或T&& amp;但在另一种情况下,T不是参考吗?有人可以告诉我确切的规则吗?我需要澄清一下!

推荐答案

如果模板参数 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&&

具有以下形式的功能模板:

A function template of the form:

  • template< class T>void f(T x)
    将推导出 T 作为对象类型(而 x 是对象类型,因此按值传递)
  • 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)

template< class T>void f(T& x)
将推导 T 作为对象类型(然后 x 具有左值引用类型)

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 具有左值引用类型)
  • 作为对象类型(因此 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&或T&&, [...]

How come in the perfect forwarding function, T turns into a T& or T&&, [...]

这是错误的. T 成为引用类型 L& 对象类型 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

  • L& (因为将左值引用添加到左值引用仍然是左值引用,就像 add_rvalue_reference< L& :: type L& )
  • 或变成 R& (因为 add_rvalue_reference< R> :: type R&&))
  • 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; amp;.或T&amp; amp; amp; amp; amp; amp; amp; amp; amp;但当您不这样做时,T根本不是参考.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆