2

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&) ?

Community
  • 1
  • 1
innochenti
  • 1,093
  • 2
  • 8
  • 23

2 Answers2

2

You could say f(static_cast<const int &>(a)>) to force the use of the int overload. The non-const overloads cannot be disambiguated by argument, but you could cast the function itself:

static_cast<void(&)(int&)>(f)(a);

(Of course you can always select a specific overload manually like this, so this isn't really "overload resolution" any more.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

You can do something like this:

int main() 
{ 
    int a = 42;
    void (*fp)(int&) = &f; // (A)
    fp(a);
} 

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:

void take_f(int)    {}
void modify_f(int&) {}

int main() 
{ 
    int a = 42;
    modify_f(a);
}

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() and modify_f().

It makes more sense this way anyway since having one function takie an int and another an int& is probably a good sign that they are doing significantly different things (and thus warrant different function names).

Community
  • 1
  • 1
In silico
  • 51,091
  • 10
  • 150
  • 143
  • so, more general question - reference is not part of type T? I mean, for asterisk it works properly. – innochenti Mar 25 '12 at 14:05
  • @innochenti: The reference *is* part of a type, but the two overloads are ambiguous, because an lvalue of type `int` can equally well bind to an `int` and to an `int&`. – Kerrek SB Mar 25 '12 at 14:08