binding error in l-value reference and r-value reference
Asked Answered
S

1

5
void f(int & i){
    cout << "l-value-ref" << endl;
}

void f(int && i){
    cout << "r-value-ref" << endl;
}

Assuming the code above, we have a overloaded function which takes respectively l-value-reference and r-value-reference parameters.

int x = 5;
f(x);
f(5);
const int j = 9;
f(j);

when i use const int j = 9 compiler gives ambiguity error. How can i solve this problem?

Sunnisunnite answered 22/2, 2017 at 12:0 Comment(7)
Change the first f() to take a const int &i parameter.Phox
I'm surprised your compiler gives you that error. Mine gives me "binding const int to reference of type int& discards qualifiers".Shortwave
If it gives ambiguity error, then I think this error is misleading because neither of them can be invoked with argument j which is of type int const. The compiler should give "no function found which accepts int const &".Mason
Or add a void f(const int &) overload. Depends on what you want to achieve.Fuzzy
but it seems that the compiler can not differentiate the r value and l value when it comes to constparameters am i right?Zymo
@RıfatTolgaKiran, no, neither of these functions is going to work. You can easily check it by commenting them 1by1. Neither of the overloads match the const int argument.\Shortwave
@Shortwave oh is my fault. the compiler gives error: binding 'const int' to reference of type 'int&' discards qualifiers error. So the only solution is to create a const int & function.Zymo
S
7

Your compiler error (if it is indeed the one you mentioned) is misleading. What is really wrong here is that attempting to pass a const int argument to any of your functions would discard the const qualifier, which is not allowed. You can solve it by either changing the signature to const int& / const int&& (note that const int&& will still not work with a const int argument), or by adding an another overload for const arguments, depending on what exactly do you want to achieve.

Basically the choice you have to make is between "I need one version that needs to be able to modify the passed reference" (2 versions then) and "I will never modify the passed reference anyway" (just the const int& version).

Shortwave answered 22/2, 2017 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.