8

Consider following code:

#include <iostream>

void foo(int m);
void foo(int &k);

int main()
{
    foo(5); // ok, because there is no ambiguity

    int m = 5;
    //foo(m); // compile-time error, because of ambiguity
    foo(m + 0); // ok, because it's an expression of type int and not object's lvalue
}

void foo(int m)
{
    std::cout << "by value\n";
}
void foo(int &k)
{
    std::cout << "by reference\n";
}

I understand that it introduces ambiguity for foo(m), but is this allowed, when expression is of type int (or another that can be converted to int)?

I have tried to find some standard reference on this, yet with no luck.


Disclaimer: Note that it's not duplicate of Function Overloading Based on Value vs. Const Reference. The const references are different as they can be assigned with rvalues, as opposite to "ordinary", non-const references.

Community
  • 1
  • 1
Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
  • 1
    `m` is also an expression of type `int`. – Kerrek SB Jul 16 '15 at 12:23
  • 1
    possible duplicate of [Function Overloading Based on Value vs. Const Reference](http://stackoverflow.com/questions/5465293/function-overloading-based-on-value-vs-const-reference) – Piotr Siupa Jul 16 '15 at 12:23

2 Answers2

9

13.1 [over.load] is pretty clear (apart from a multi-page note) about which functions cannot be overloaded in the same scope.

Your case is not listed there, and you can declare those overloads, you just can't necessarily use them easily. You could call the lvalue one like so:

void (*f)(int&) = foo;
f(m);

This avoids the ambiguity that happens when you call foo(m).

Aside: another way to write foo(m + 0) is simply foo(+m), the unary + operator converts the lvalue to an rvalue, so the foo(int) overload is called.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
7

Yes, it is allowed.

There is no rule to prevent this overload.

[C++14: 13.1/1]: Not all function declarations can be overloaded. Those that cannot be overloaded are specified here. [..]

[C++14: 13.1/2]: (blah blah lots of exceptions not including any for this case)

It would be extremely limiting for the language to prohibit function overloads that may be ambiguous in certain scenarios with certain calls, and for no good reason I might add!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055