using...">

Calling an overloaded lithium floating-point function gives an "ambiguos" error

When compiling the following code:

#include <iostream>
using namespace std;

void print(int i){
    cout << i << endl;
}

void print(float i){
    cout << i << endl;
}

int main(){
    print(5);
    print(5.5)
    return 0;
}

I get an error message:

the call to the overloaded 'print (double)' is ambiguous.

However, if I change

void print(float i){

to

void print(double i){

The code compiles. Why is this?

+4
source share
3 answers

Try another exercise to figure this out. Removing one of the two overloads will make the program compile, although the identity matches for a literal 5.5, a double value, it can be implicitly converted to intor float.

, 5.5 int float, . , , , .

a float, 5.5f , float . , double, 5.5, float double , .

+5

, 5.5 double. print , , , , , . , :

, .. void print(double); .

, . A double int, float, .

, , , .

, : print(5.5f);   , double, ,

void print (double);
void print (const double&);
template <class T>
void print (T);
+4

Integer version:

void print(int i)
           ^^^ // This declaration wants an `int` type

Floating version:

void print(float i)
           ^^^^^ // This declaration wants a `float` type

Using:

print(5); // Calling print with `int`, finds the "Integer version"
print(5.5); // '5.5' is a `double` type, which is neither an `int` type nor a `float` type

Since the type is specified doubleand there is no overload double, conversion to intor is required to use existing overloads float.

Using existing overloads:

 print(5.5f); // Use a `float` literal (i.e., this is a `float` type)
 print(static_cast<float>(5.5)); // I'd recommend the former but this works
 print(static_cast<int>(5.5)); // Works but obviously truncates the value

Add a new overload (as opposed to updating an existing overload float):

void print(double i); // A new overload declaration
+3
source

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


All Articles