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?
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With