如何解决具有模板和右值引用的重载解析
此重载解决方案行为使我感到困惑:
function OpenNav() {
document.getElementById('lateralNav').style.animation = 'MenuEntrar 0.5s';
}
ReactDOM.render(
<div className="barra-lateral" id="lateralNav" onClick={OpenNav()}>,document.getElementById('root')
);
输出:
#include "stdio.h"
template<class T>
class C
{
public:
C(T v): m(v) {};
T m;
template<class U>
T f(U &&p)
{
printf("rRef called.\n");
return p;
}
template<class U>
T f(const U &p)
{
printf("const Ref called.\n");
return p;
}
};
int main()
{
C<int> a(5);
a.f<int&>(a.m);
a.f(a.m);
return 0;
}
在gdb或Visual Studio中调试时,两个调试器均显示
在这两种情况下都调用const Ref called.
rRef called.
,但是显式模板解析解析为预期的const ref,而第二种解析为右值引用。为什么?为什么编译器甚至不尝试
int C<int>::f<int &>()
我认为这很明显?
右值引用如何绑定到成员值? int C<int>::f<int>()
不是左值吗?
解决方法
拨打电话时:
a.f<int&>(a.m);
编译器必须在以下候选者之间进行选择:
template<class U>
T f(U && p); // #1
template<class U>
T f(U const & p); // #2
对于此过载解决过程,首先将两个模板转换为参数int&
。
将U = int &
替换为#1
会得到int & &&
,由于引用崩溃,它变成了int &
。
类似地,将U = int &
替换为#2
会得到int & const &
,由于引用崩溃,它又变成int &
。
现在,由于两个重载都匹配,因此使用部分排序来确定要调用的模板。现在U const &
比U &&
更具专业性。这是因为U &&
可以绑定到U const &
可以绑定的所有类型,但是反之则不成立。
因此,由于#2
更专业,因此它在重载解析中获胜并被调用。
在此次通话中:
a.f(a.m);
未指定 模板参数。这意味着#1
的参数被认为是转发引用,并且它与传入的所有类型匹配,因此#1
被调用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。