2

I got a problem with function overloading, probably very stupid and simple, but cant come up with the solution. I defined 2 overloaded functions:

void pp(int) {cout << "1";}
void pp(int&) {cout << "2";}

and later im trying to call them. Calling first one is easy, for example pp(1); Temporary object cant be assigned to non-const reference, so there is no ambguity. But what should I write to call function pp(int&)? I have really no idea. A compiler let for such overloading so I guess there is a way to call both functions. Otherwise it would be pointless to let for such overloading.

Another similar problem looks like follows:

void p(const int) {cout << "1";}
void p(const int&) {cout << "2";}

Compiler let for such overloading, but I have no idea how to call any function without ambiguity. Any clues?

EDIT: This is just an example to think about it, not to use that in real program or something. The code presented here is obviously ugly and only shows some kind of problem.

The main conclusion should be that its the programmer who should take care of ambiguity even if a compiler lets for some overloadings.

0

1 Answer 1

2

You can always override overload resolution with an explicit cast of the function:

int x = 10;
static_cast<void(&)(int&)>(pp)(x);     // calls void pp(int&)

Otherwise, indeed, the call pp(x) is ambiguous, because binding to a reference has exactly the same "matching priority" as binding to a value in terms of overload resolution. The same holds if the second overload is pp(const int &), since "qualification adjustments" are also "exact matches".

See "Standard conversion sequences" [over.ics.scs] in the standard (e.g. 13.3.3.1.1 in C++11), and "Reference binding" [over.ics.ref] (13.3.3.1.4).

Sign up to request clarification or add additional context in comments.

4 Comments

looks some ugly, but +1 because I didn't know how to do it
One of the goals of overloading is making code easier to read and write. I prefer not to use this invocation and simply write void pp2(int&) and then call it by pp2(x) -- BTW this casting is interesting.
Thats more or less what I expected. There is no way that the result of implicit resolution will be the function pp(int&).
@Givi: No, the problem is that there are more than one viable overloads which are equally good matches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.