Assuming we have this example of functions in C ++
void foo(int x) { std::cout << "foo(int)" << std::endl; }
void foo(int& x) { std::cout << "foo(int &)" << std::endl; }
Is there a possibility to differentiate which function I want to invoke by making some modification in the call arguments?
If the foo function is invoked in any of these modes:
foo( 10);
i = 10;
foo( static_cast<const int>(i));
foo( static_cast<const int&>(i)); // Aunque aquí convertir un tipo básico a través de una referencia no tiene mucha utilidad. Sólo es para exponer los casos posibles.
Invokes the first of the two overloaded functions, because a constant argument can not be passed to a non-constant parameter. But how would it be done to invoke the second of the overloaded functions? If I make the following invocation:
int i = 10;
foo( i);
An ambiguity error occurs because both functions are valid for this argument.
In this link link exposes that a way to solve it is, in the case of handling objects instead of basic types , make the copy constructor private so that, since it can not make a copy of the value, it must obligatorily invoke the second function and pass the object by reference. But what about the basic types? Do you have to change the name of the functions to avoid this kind of problems?