Possible Duplicate:
«F(5)» and «int x; F(x)» to call different functions?
Can we overload a function based on only whether a parameter is a value or a reference?
Let’s say we have function f with different parameters:
void f(int)
{
}
void f(int&)
{
}
int main()
{
int a = 42;
f(a);
}
How to make call of void f(int&) ?
You can do something like this:
Here, we’re taking a function pointer to one of the overloaded functions
f. As explained in my answer to another question, the compiler will select the proper function to make line (A) work. Note that I didn’t use a cast; that way if I change the function signatures such that the above doesn’t work the compiler will issue an error instead of potentially allowing the code to invoke undefined behavior.Although for this situation, it’s better to simply give the two functions different names. Like so:
This allows for code with a clearer intent and you won’t have overloading issues. Of course, you can come up with better names than
take_f()andmodify_f().It makes more sense this way anyway since having one function takie an
intand another anint&is probably a good sign that they are doing significantly different things (and thus warrant different function names).