How to allow a function call when overloading a method?

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 the program, then it works fine.

 int i = 10; float j = 1.0; add(i,f); // working 

Why using an unsigned variable in an overload function causes an ambiguios call

+7
source share
4 answers

In C ++, nothing is called unsigned float . float always signed

According to the C ++ Standard Table in section 7.1.5.2, β€œsigned” is itself a synonym for β€œint”. Therefore, the compiler should inform you of the error that signed or unsigned not applicable for float .

Check here , even Ideone reports an error.

 error: 'signed' or 'unsigned' invalid for 'j' 

Are you misinterpreting this error as an error in the ambiguos function ambiguos ?

If you release unsigned float , the compiler will not be able to see any corresponding function call that has unsigned int and float arguments, so it pushes unsigned int to int and allows function call with int and float arguments, there is no ambiguity.

Here is an example code for Ideone.

+7
source

The call is ambiguous because none of your function signatures match (due to searching for signed values), and if it starts casting, it can match multiple signatures, so it doesn't know what you want. Add overloads for unsigned values ​​to avoid confusion. (Not so sure about the unsigned float!)

+1
source

In C ++, int means it is signed. Thus, when you call with unsigned int, he sees that there is no corresponding function call, and he tries to introduce the unsigned int method into a value for which a match can occur, but here he cannot decide what type of data he should promote itself, since unsigned int can be promoted in both int and float. (I'm not sure about this "Unsigned float")

0
source

In C ++, an unsigned float is treated as an unsigned int, and part of the fraction is truncated. Therefore, when you call add (i, f), it has no function to match.

0
source

All Articles