void add(int,int);
void add(int ,float);
void add(float,int);
unsigned int i = 10;
unsigned float j = 1.0;
add(i,f); // ambiguios call error
if i remove unsigned from program then it is wo开发者_StackOverflowrking fine.
int i = 10;
float j = 1.0;
add(i,f); // working
Why using unsigned variable in overloading function causes ambiguios call
There is nothing called as unsigned float
in C++. float
is always signed
As per, C++ Standard table 7 in §7.1.5.2, "signed" by itself is a synonym for "int".
So the compiler should give you a error, that signed
or unsigned
is not applicable for float
.
Check here, even Ideone reports an error.
error: ‘signed’ or ‘unsigned’ invalid for ‘j’
Are you by any chance misinterpreting this error as ambiguos
function call error?
If you drop the unsigned float
, the compiler cannot see any matching function call which has arguments unsigned int
& float
, So it promotes unsigned int
to int
and resolves the call to the function with arguments int
& float
, there is no ambiguity.
Here is the code sample on Ideone.
The call is ambiguous because none of your function signatures match (due to looking for signed values) and if it starts casting then it could match more than one signature, so it doesn't know which you want. Add overloads for unsigned values to avoid confusion. (Not so sure about unsigned float!)
In C++, int means it is signed. So, when you call with an unsigned int, it sees that there is no matching function call, and it tries to type promote unsigned int to something for which a match may occur, but here, it is unable to decide to which data type it must promote itself since unsigned int can be promoted to both int and float. (I'm not sure about that "Unsigned float")
In C++ unsigned float is treated as unsigned int and the fraction part is truncated. Hence, when you call add (i, f) it has no function to match.
精彩评论