使用有符号和无符号 r 值引用进行函数重载

kad*_*ina 4 c++

我试图理解函数重载中的 r 值引用,如下面的代码所示。

#include <iostream>

using namespace std;

void test(int && n) {
    cout << "in test int &&" << endl;
}

void test(unsigned int && n) {
    cout << "in test unsigned int &&" << endl;
}

int main() {
    unsigned int n = 5;
    test(std::move(n)); // ---> 1
    test(n);            // ---> 2
    test(5);            // ---> 3

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

下面是输出

in test unsigned int &&
in test int &&
in test int &&
Run Code Online (Sandbox Code Playgroud)

输出行 1 是预期的,输出行 3 也是预期的,因为默认 int 有符号。但不明白输出第 2 行。当我调用 时test(n),我期望它会调用,test(unsigned int && n)因为 n 是无符号的,而不是test(int && n)被调用。任何人都可以告诉我为什么test(int && n)会接到电话吗?

Ted*_*gmo 8

test(n);不能使用void test(unsigned int&&). 该函数将尝试将右值引用绑定到左值。

然后,编译器尝试通过转换来查找匹配项n,并发现它可以转换n为 an int(然后变为右值)来获得匹配项,因此void test(int&&)获胜。