通用引用和转发引用之间有区别吗?
Is there a difference between universal references and forwarding references?
此函数的参数将绑定到右值引用:
void f(int && i);
但是,此函数的参数将绑定到右值或左值引用:
template <typename T>
void f(T && t);
我经常听说这被称为通用参考。
我也听说它被称为转发参考。
他们的意思是一样的吗?
如果函数体调用std::forward
是否只是一个转发引用?
不幸的是,这很混乱,但它们只不过是同一事物的两个名称。
迈耶斯很久以前就提出了通用引用(我猜)(参见 here 作为示例)。
转发参考直接从 standardese 中获取。就这些了。
Do they mean the same thing?
Universal reference 是 Scott Meyers 创造的一个术语,用于描述对 cv 非限定模板参数采用右值引用的概念,然后可以将其推导为值或左值引用。
当时 C++ 标准对此没有专门的术语,这是 C++11 中的一个疏忽,很难教授。 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.
因此,两者是一个意思,目前的C++标准术语是转发引用。论文本身阐明了为什么 "forwarding reference" 比 "universal reference."
更好
Is it only a forwarding reference if the function body calls std::forward
?
不,您对转发引用所做的操作与名称无关。概念转发引用只是指类型 T
是如何推导出来的:
template <class T> void foo(T&& ); // <==
不需要后续转发。
此函数的参数将绑定到右值引用:
void f(int && i);
但是,此函数的参数将绑定到右值或左值引用:
template <typename T>
void f(T && t);
我经常听说这被称为通用参考。
我也听说它被称为转发参考。
他们的意思是一样的吗?
如果函数体调用std::forward
是否只是一个转发引用?
不幸的是,这很混乱,但它们只不过是同一事物的两个名称。
迈耶斯很久以前就提出了通用引用(我猜)(参见 here 作为示例)。
转发参考直接从 standardese 中获取。就这些了。
Do they mean the same thing?
Universal reference 是 Scott Meyers 创造的一个术语,用于描述对 cv 非限定模板参数采用右值引用的概念,然后可以将其推导为值或左值引用。
当时 C++ 标准对此没有专门的术语,这是 C++11 中的一个疏忽,很难教授。 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.
因此,两者是一个意思,目前的C++标准术语是转发引用。论文本身阐明了为什么 "forwarding reference" 比 "universal reference."
更好Is it only a forwarding reference if the function body calls
std::forward
?
不,您对转发引用所做的操作与名称无关。概念转发引用只是指类型 T
是如何推导出来的:
template <class T> void foo(T&& ); // <==
不需要后续转发。