C ++ ambiguous call of an overloaded function with unsigned int

This seems inconsistent. I have 3 f functions overloaded for signed types short , int and long long . If you pass unsigned short , it will be translated to the next largest signed int . However, if you pass an unsigned int , then it does not get promoted to the signed long long , which is what I would expect, rather, the compiler complains about the ambiguous call of the overloaded function.

 void f(short x) { std::printf("f(short)\n"); } void f(int x) { std::printf("f(int)\n"); } void f(long long x) { std::printf("f(long long)\n"); } int main() { f((unsigned short)0); // Fine: calls f(int) // f((unsigned int)0); // Ambiguous: could be f(short), f(int) or f(long long) } 
+6
source share
2 answers

It's inconsistent, yes, but it's "The Way The Language Is", and you need to handle it, for example. if you want f((unsigned int)0) call overload long long , then provide a wrapper,

 inline void f(unsigned int x) { f((long long)x); } 

C ++ designers would ideally resemble both of your cases to cope with overloading. But there was this legacy (starting with "K & R" C), called "advancement of default arguments", which, in essence, says that the compiler will implicitly convert all integer types narrower than int to int if necessary to match function signature, and all floating point types are already double to double ditto.

So really, this is the case of f((unsigned short)0) , which is a strange person.

+6
source

http://en.cppreference.com/w/cpp/language/implicit_conversion

Integral promotion does not allow you from unsigned int to long long .

Integral promotion makes for you from unsigned short to int .

The integral conversion from unsigned int is considered equally good for your overloads.

Promotion ends with int and / or unsigned int if your source type is not enum , which requires a larger integral type.

Promotion is preferable to conversion, so your first case is unambiguous. In the second case, there is no way forward, so your code is ambiguous.

+4
source

Source: https://habr.com/ru/post/1011727/


All Articles