Home > Software engineering >  function overloading with signed and unsigned r value reference
function overloading with signed and unsigned r value reference

Time:01-25

I was trying to understanding r value reference in function overloading as in the code below.

#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;
}

Below is the output

in test unsigned int &&
in test int &&
in test int &&

output line 1 is expected and output line 3 is also expected as default int is signed. But didn't understand output line 2. When I call test(n), I expected it to call test(unsigned int && n) as n is unsigned instead test(int && n) is getting called. Can any one please let me know why test(int && n) is getting called.

CodePudding user response:

test(n); can't use void test(unsigned int&&). The function would try to bind an rvalue reference to an lvalue.

The compiler then tries to find a match via conversion of n and finds that it can convert n to an int (which then becomes an rvalue) to get a match, hence void test(int&&) wins.

  •  Tags:  
  • c
  • Related