Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 function overloading with references [duplicate]

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 850
Carlos A. Gómez Avatar asked Nov 30 '25 02:11

Carlos A. Gómez


2 Answers

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

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

Demo

like image 134
Jarod42 Avatar answered Dec 02 '25 16:12

Jarod42


In most instance, function overloading involves distinct parameter types and different input parameter lengths.

Your attempt is generally a bad practice and the resulting compiled code is compiler dependent and code optimization may even worsen things even more.

You may consider simply adding a second parameter to the second method, something like this:

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

where ... could be a boolean type, say: bool anotherFunction

So calling foo(param1, param2) would simply call the second code and everybody is fine.

like image 27
Gamma.X Avatar answered Dec 02 '25 16:12

Gamma.X



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!