通用引用和转发引用之间是否存在区别?

发布于 2025-02-09 06:45:58 字数 306 浏览 3 评论 0原文

该功能的参数将绑定到rvalue参考:

void f(int && i);

但是,此功能的参数将绑定到rvalue或lvalue参考:

template <typename T>  
void f(T && t);

我经常听到这是通用参考。
我也听说过它被称为转发参考。
他们的意思是同一件事吗?
如果功能主体调用std :: forward,它是否仅是转发引用?

An argument to this function will bind to an rvalue reference:

void f(int && i);

However, an argument to this function will bind to either an rvalue or an lvalue reference:

template <typename T>  
void f(T && t);

I've often heard this referred to as a universal reference.
I've also heard it been called a forwarding reference.
Do they mean the same thing?
Is it only a forwarding reference if the function body calls std::forward?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

才能让你更想念 2025-02-16 06:45:58

他们的意思是同一件事吗?

通用参考是一个术语Scott Meyers,以描述采取行动的概念对CV UNCALIFIED模板参数的RVALUE引用,然后可以将其推导为值或LVALUE参考。

当时,C ++标准对此没有特殊的术语,这是C ++ 11中的监督,因此很难教书。 n4164 添加了以下定义, to [temp.deduct]

a 转发参考是对CV UNqualified模板参数的RVALUE参考。如果p是转发引用,并且该参数是lvalue,则使用类型为“ lvalue参考”。

因此,这两个表示同一件事,当前的C ++标准项是转发参考。本文本身表达了为什么“转发参考”比“普遍参考”更好。

如果功能主体调用std :: forward

,它只是转发引用

不,您使用转发参考的工作与名称无关。概念转发引用简单地指出了如何推导以下类型t

template <class T> void foo(T&& ); // <== 

以后不需要转发。

Do they mean the same thing?

Universal reference was a term Scott Meyers coined to describe the concept of taking an rvalue reference to a cv-unqualified template parameter, which can then be deduced as either a value or an lvalue reference.

At the time the C++ standard didn't have a special term for this, which was an oversight in C++11 and makes it hard to teach. This oversight was remedied by N4164, which added the following definition to [temp.deduct]:

A forwarding reference is an rvalue reference to a cv-unqualified template parameter. If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction.

Hence, the two mean the same thing, and the current C++ standard term is forwarding reference. The paper itself articulates why "forwarding reference" is a better term than "universal reference."

Is it only a forwarding reference if the function body calls std::forward?

Nope, what you do with a forwarding reference is irrelevant to the name. The concept forwarding reference simply refers to how the type T is deduced in:

template <class T> void foo(T&& ); // <== 

It does not need to be subsequently forwarded .

悲凉≈ 2025-02-16 06:45:58

不幸的是,这很令人困惑,但它们不过是同一件事的两个名字。
迈耶斯(Meyers)提出了通用参考(我猜)很久以前(请参阅在这里例如)。
转发参考直接从 standardese 中获取。就这样。

Unfortunately, it's confusing, but they are nothing more than two names for the same thing.
Universal reference was proposed (I guess) by Meyers far ago (see here as an example).
Forwarding reference is picked up directly from the standardese. That's all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文