为什么添加const将通用引用作为右值 [英] Why adding `const` makes the universal reference as rvalue

查看:297
本文介绍了为什么添加const将通用引用作为右值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Scott的上一本有关c ++ 11和14的杰作中的通用引用,尽管尽管将参数分配给左值或右值类型引用参数,但在两者之间还是有一些东西被称为通用引用,可以根据传递的参数的类型特征推导出为l/rvalue.我能理解是什么使该参数成为通用引用,但我不清楚的一件事是为什么在类型参数const T&& p中添加const会使p成为右值:

I have been reading about the universal references in Scott's last master piece about the c++11 and 14 with that being said despite an argument assigned to either lvalue or an rvalue type reference parameter there is something in between called universal reference which could deduced to either l/rvalue based on the type trait of an argument that passed . I could understand what makes the parameter as an universal reference but the one thing that doesn't clear to me is why adding const to the type parameter const T&& p make the p as rvalue:

template<typename T>
void f(T&& param); // param is an universal reference

template<typename T>
void f(const T&& param); // param is an rvalue reference

const在分配给参考参数时是否会做更多的事情.

Does the const do more than this when assigned to the reference parameter.

推荐答案

正式名称不是通用参考,而是 标准 指出,只有右值引用 cv不合格模板参数属于此类别:

The official name is not universal reference, but forwarding reference. The Standard states that only rvalue references to cv-unqualified template parameters fall in this category:

14.8.2.1从函数调用[temp.deduct.call]中推导模板参数

3如果P是符合简历的类型,则该类型的顶级cv限定词 对于类型推导将被忽略.如果P是参考类型,则该类型 P所指代用于类型推导. 转发参考是 如果P为a,则为对cv不合格模板参数的右值引用. 转发引用,并且参数是左值,类型为左值" 引用A"代替A进行类型推导. [示例:

3 If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. 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. [ Example:

template <class T> int f(T&& heisenreference);
template <class T> int g(const T&&);
int i;
int n1 = f(i); // calls f<int&>(int&)
int n2 = f(0); // calls f<int>(int&&)
int n3 = g(i); // error: would call g<int>(const int&&), which
               // would bind an rvalue reference to an lvalue

—结束示例]

允许const T&&用作转发引用,将使得无法重载仅将右值引用作为参数的模板函数.

Allowing const T&& to behave as forwarding references, would make it impossible to overload a template function who takes only an rvalue reference as parameter.

更新:正如@HowardHinnant在评论中提到的,const T&&确实有其用途(另请参见 此问题与解答 ).

Update: as @HowardHinnant mentions in the comments, const T&& does have its uses (see also this Q&A).

这篇关于为什么添加const将通用引用作为右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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