具有模板和右值引用的重载解析

问题描述

此重载解决方案行为使我感到困惑:

    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被调用。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...