转发非引用类型的引用 [英] Forwarding references for non-reference types

查看:80
本文介绍了转发非引用类型的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 template<typename T>
 void F(T&& x) {}

如果我们使用int&类型的参数来调用它一切都很清楚-引用崩溃了,我们仍然有左值引用.但是,如果我们使用例如int参数来调用它,将会发生什么.我的想法:我们推导出类型T = int,并用rvalue-reference装饰它,所以F取int&&参数并以int类型调用它会导致错误.但是在实数F中,将这样的参数称为左值引用.左值引用来自哪里?编译器对获取int& amp;应用了哪些规则来自int?

If we call it with argument of type int& everything is clear - reference collapsing takes place and we still have lvalue-reference. But what happens if we call it with, for example, int argument. My thoughts: we have deduced type T=int, decorate it with rvalue-reference, so F takes int&& argument and calling it with int type will result in error. But in real F takes such argument as lvalue-reference. Where does lvalue-reference come from? What rules did compiler apply to get int& from int?

推荐答案

自C ++ 17起,C ++标准中就有转发参考的概念.通常,模板参数被推导为非参考.但是对于转发参考的特定情况,如果相应的参数是左值,则推导该参数作为参考. C ++标准(N4700)[temp.over.deduct.call]/3 :

Since C++17, there is the concept of forwarding reference in the C++ standard. Normaly the template parameter is deduced as a non reference. But for the specific case of a forwarding reference if the corresponding argument is a lvalue, the parameter is deduced as a reference. C++ standard (N4700)[temp.over.deduct.call]/3:

[...] 转发引用是对cv不合格模板参数的右值引用,该参数不表示类模板的模板参数(在类模板参数推导过程中([over.match.class.deduct]).如果P是转发引用,并且参数是左值,则使用类型对A的左值引用"代替A进行类型推导.[...]

[...]A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])). 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 ++ 11(N337)

For the concern of function call, it has the same meaning as this equivalent paragraph in the C++11(N337) and C++14(N414) [temp.over.deduct.call]/3:

[...]如果P是对cv不合格模板参数的右值引用,而参数是左值,则使用类型对A的左值引用"代替A进行类型推导[...]

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

这篇关于转发非引用类型的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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