0

If there is an rvalue reference in a function overload, how to call to function? Why not call the version of the rvalue reference?

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

void test(const int &x) {
    cout << "const int &x" << endl;
}

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

void test(const int&& x) {
    cout << "const int &&x" << endl;
}

int main() {
    int &&rr = 10;
    const int &&crr = 10;
    test(rr); // call to int &x, why not call to int &&x
    test(crr); // call to const int &x, why not call to const int &&x
}

In addition, why call to 'test' is ambiguous?

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



void test(const int&& x) {
    cout << "const int &&x" << endl;
}

int main() {
    int &&rr = 10;
    test(10); // call to 'test' is ambiguous
    test(move(rr));
}
CAFBA
  • 1
  • 1
  • 1
    Even given that, in your original question you ask why `test(rr);` makes a call to the `int&` overload, but there is no such function as `test(int&& x)`. Were all four functions supposed to be `test` instead of `increment`? – Nathan Pierson Nov 02 '22 at 15:43
  • 1
    rr and crr are named variables, they are lvalues. Thus, int &x and const int &x are selected. – 273K Nov 02 '22 at 15:43
  • @Nathan Pierson ,Sorry, it is supposed to be test – CAFBA Nov 02 '22 at 15:52
  • @273K So,if pass-by-references, the function call should be judged by considering the lvalue and rvalue – CAFBA Nov 02 '22 at 15:59

0 Answers0