1

Consider the following function definitions:

void fun(int& a)
{
    cout << "Ra" << endl;
}

And:

void fun(int a)
{
    cout << "a" << endl;
}

Now, when I call the function like this:

int a;
fun(a);

The call is ambiguous, because the compiler can't decide whether to call by value or by reference.

My Question is:

When I write something like this:

int a;
int &b = a;
fun(b);

It again gives ambiguity. Since b is a reference, so why not call the one where the argument is a reference.

I already saw the answers in this question: Function Overloading Based on Value vs. Const Reference but it doesn't answer my question. Please Help.

Community
  • 1
  • 1
tapananand
  • 4,392
  • 2
  • 19
  • 35
  • BTW: Why do you use the `int&` `b` in your example? Completely superfluous. – Deduplicator Nov 15 '14 at 09:08
  • @Deduplicator: I am using int&, to see why does the compiler allow both int and int& functions to be created. How can we call them in any way without creating ambiguity. – tapananand Nov 15 '14 at 09:11
  • Read *all* the answers to the duplicate, that should be sufficient. BTW: There's also cast-to-xvalue. – Deduplicator Nov 15 '14 at 09:14
  • The duplicate answers one part of my doubt that is how can we call the reference version. But why passing b as argument gives ambiguity here? – tapananand Nov 15 '14 at 09:26
  • 1
    Because `b` is an lvalue of type `int`. And both functions are equally good matches for that. (See it not as a reference, but as simply an alias - another name - for `a`. For nearly all purposes, it is. (Exception for `decltype`.)) – Deduplicator Nov 15 '14 at 09:28

0 Answers0