此函数的参数将绑定(bind)到右值引用:
void f(int && i);
但是,此函数的参数将绑定(bind)到右值或左值引用:
template <typename T>
void f(T && t);
我经常听说这被称为通用引用。
我也听说它被称为转发引用。
他们的意思是一样的吗?
如果函数体调用std::forward
,是否只是转发引用?
最佳答案
Do they mean the same thing?
Universal reference是 Scott Meyers 创造的一个术语,用于描述将右值引用应用于 cv 非限定模板参数的概念,然后可以将其推断为值或左值引用。
当时 C++ 标准对此没有专门的术语,这是 C++11 中的一个疏忽,因此很难教授。 N4164 纠正了这种疏忽。 ,将以下定义添加到 [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++ 标准术语是转发引用。论文本身阐明了为什么“转发引用”比“通用引用”更好。
Is it only a forwarding reference if the function body calls
std::forward
?
不,您对转发引用所做的操作与名称无关。概念转发引用只是指T
类型是如何推导出来的:
template <class T> void foo(T&& ); // <==
不需要后续转发。
关于c++ - 通用引用和转发引用之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552272/