I’m reading Stroustrup’s book, the section on overloading and related ambiguities.
There’s an example as follows:
void f1(char);
void f1(long);
void k(int i)
{
f1(i); //ambiguous: f1(char) or f1(long)
}
As the comment states, the call is ambiguous.
Why?
The previous section in the book stated 5 rules based on matching formal and actual parameters. So shouldn’t the above function call come under rule 2, regarding “promotions”?
My guess was that ‘i’ should be promoted to a long, and that’s that.
As per the comment, it seems that a int to char conversion (a demotion?) also comes under rule 2?
Anything goint from int above isn’t a promotion anymore. Anything going less than int to int is a promotion (except for rare cases – see below)
So if you change to the following it becomes non-ambiguous, choosing the first one
Notice that this is only true on platforms where
intcan store all values ofunsigned short. On platforms where that is not the case, this won’t be a promotion and the call is ambiguous. On such platforms, the typeunsigned intwill be the promotion target.Sort of the same thing happens with floating points. Converting
floattodoubleis a promotion, butdoubletolong doubleisn’t a promotion. In this case, C++ differs from C, wheredoubletolong doubleis a promotion likewise (however, it doesn’t have overloading anyway).