CarlosUrda CarlosUrda - 7 months ago 26
C++ Question

Function overloading in C++ passing arguments by value or by reference

If we have this example functions code in C++

void foo(int x) { std::cout << "foo(int)" << std::endl; }
void foo(int& x) { std::cout << "foo(int &)" << std::endl; }

Is it possible to difference what function to call doing any modification in the calling arguments?

If the function foo is called in some of these ways:

foo( 10);

i = 10;
foo( static_cast<const int>(i));

foo( static_cast<const int&>(i));

it's called the first foo overloaded function, because it can't pass by reference a const argument to a non-const parameter.
But, how would you do to call the second foo overload function?
If I call the next way:

int i = 10;
foo( i);

It happens an ambiguous error because both functions are valid for this argument.

In this link it's explained one way to resolve it: using objects instead of built-in types and doing private the copy constructor, so it can't do a copy of object value and it has to be called the second foo overload function and passing the object by reference. But, is there any way with the built-in types? I have to change the name of function to avoid the overloading?


You may do a cast (of the function) to select the overload function:

static_cast<void (&)(int&)>(foo)(i);