Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 https://stackoverflow.com/a/5465379/6717386 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?

like image 696
Carlos A. Gómez Avatar asked Aug 15 '16 14:08

Carlos A. Gómez


1 Answers

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

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

Demo

like image 168
Jarod42 Avatar answered Sep 17 '22 16:09

Jarod42