Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting overload to reference-accepting function

In the following code I'm defining two overloads, one accepting an integer and the other a reference to an integer...

#include <stdio.h>

void foo(int)  { printf("foo(int)\n"); }
void foo(int&) { printf("foo(int&)\n"); }

Then I'm trying to call the two overloads

int main(int argc, const char *argv[]) {
    foo(3);     // Calls foo(int)
    int x = 3;
    foo(x);     // <--- compilation error (ambiguous overload)
    int& y = x;
    foo(y);     // <--- still ambiguous
    return 0;
}

The question is... how can the int& overload be selected?

If it cannot be called, what is the point of compiling it?

like image 373
6502 Avatar asked Nov 14 '25 19:11

6502


1 Answers

how can the int& overload be selected?

Using a function pointer:

using fptr = void (*)(int&);
fptr f = foo;
int i;
f(i);

And for those who wander here, looking for a way to overload lvalues and rvalues sensibly, the solution is to use rvalue references:

void foo(int&&) { printf("foo(int&&)\n"); }
void foo(int&)  { printf("foo(int&)\n"); }
like image 175
eerorika Avatar answered Nov 17 '25 16:11

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!