Reputation: 175
I am trying to create a simple (absolute) function in c++, I have created two functions with the same name one that takes an integer and returns an integer and one that takes a float and returns a float but every time I try to run the code I receive this error:
"error: call of overloaded 'absolute(double)' is ambiguous"
I tried changing the input parameters of the second function so that it takes a double and returns a float and the code ran perfectly, I'd like to know why the code won't run when the parameters and return type are both set to float, thank you.
#include <iostream>
#include <fstream>
using namespace std;
int absolute(int x){
if (x<0){
x=-x;
}
return x;
}
float absolute (float x)
{
if (x<0){
x=-x;
}
return x;
}
int main( )
{
cout << absolute(3.5);
}
Upvotes: 0
Views: 300
Reputation: 23
you write that 3.5 is a float this value is not a float it is a double.
Upvotes: 1
Reputation: 206577
The type of the literal 3.5
is double
, not float
.
Choosing either of the overloads would require a conversion. Hence the ambiguity.
You can use 3.5f
to make it a float
literal.
cout << absolute(3.5f);
A better solution, IMO, would be to use a function template.
template <typename T>
T absolute(T x)
{
return (x < 0 ? -x : x);
}
Upvotes: 3
Reputation: 409166
Read that error message again. Notice how it says double
as the argument type it want to use.
That's because floating point constants like 3.5
are of type double
. And the compiler don't know if it should convert the double
value to an int
or a float
, thereby giving you the error.
If you want to call the float
overload, use 3.5f
to make it a float
value. Or change your overload to use type double
instead of float
.
Upvotes: 1