Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overload ambiguity: conversion versus promotion with primitive types

In this code:

void f(float f, long int i) { cout << "1" << endl; }
void f(float f, float d) { cout << "2" << endl; }

int main() {

   f(5.0f, 5);

}

there's an ambiguity. Check it out!. However, the second argument is a signed integer. Binding an int to a long int parameter requieres a promotion, but to float, a conversion.

Since the first argument is an exact match regarding both overloads, it doesn't count. But regarding the second parameter, its rank on the first overload (promotion) is better than the rank on the second (conversion).

Why is there a resolution ambiguity, instead of choosing the first overload?

like image 554
Peregring-lk Avatar asked Jan 08 '23 13:01

Peregring-lk


2 Answers

int to long is a conversion. short to int is a promotion. (See [conv.prom] for the full list of integral promotions.)

Similarly, float to double is the floating point promotion. double to long double is a conversion.

like image 119
T.C. Avatar answered Jan 17 '23 06:01

T.C.


5 is by default of type int. So you have conversions in both cases:

  • int to long int (aka long)
  • int to float

1) long is not compatible with int, because on certain data models their size may differ.

2) int to float is a conversion defined as "Floating - integral conversions":

Integer or unscoped enumeration type can be converted to prvalue of any floating-point type. If the value can not be represented correctly, it is implementation defined whether the closest higher or the closest lower representable value will be selected.

like image 20
Mateusz Grzejek Avatar answered Jan 17 '23 07:01

Mateusz Grzejek