Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with passing by reference

Can I overload a function which takes either a reference or variable name?

For example when I try to do this:

void function(double a);
void function(double &a);

I would like the caller of this function to be able to do:

double a = 2.5;
function(a); // should call function(double &a)
function(2.3); // should call function(double a)

I would like to write pass-by-reference functions for better memory use and possible manipulation of the variable outside of scope, but without having to create a new variable just so I can call the function.

Is this possible?

Cheers

like image 966
Simon Walker Avatar asked Jul 12 '10 09:07

Simon Walker


2 Answers

I think you're missing the point here. What you really should have is JUST this:

void function(const double &a);

Note the "const". With that, you should always get pass-by-reference. If you have non-const pass by reference, then the compiler will correctly assume that you wish to modify the passed object - which of course is conceptually incompatible with the pass-by-value variant.

With const references, the compiler will happily create the temporary object for you behind your back. The non-const version doesn't work for you, because the compiler can only create these temporaries as "const" objects.

like image 178
Roddy Avatar answered Sep 29 '22 23:09

Roddy


I tried it, and it failed

At least in MSVC2008, this is not possible - and I think this applys to all c++ - Compilers.

The definiton itself is valid, but when trying to call the function

function(a);

with a variable as a parameter, an compiler error is raised as the compiler is unable to decide which function to use.

like image 29
sum1stolemyname Avatar answered Sep 30 '22 00:09

sum1stolemyname