Reputation: 9906
The following:
#include <cmath>
int main()
{
float base = 2.0f;
float result = std::pow(base, 2);
return 0;
}
Triggers a -Wconversion
warning in case it is turned on. Wandbox
It seems that the double
overload of std::pow
is invoked, where I would expect the float
overload to be chosen (with the int
exponent being cast to float
). Can someone who knows his overloads please explain why?
Upvotes: 4
Views: 420
Reputation: 24946
Since C++11, mixed argument pow
has any integral argument cast to double. The return type of the mixed argument functions is always double
except when one argument is long double
then the result is long double
.
[c.math]
In addition to the double versions of the math functions in , C++ adds float and long double overloaded versions of these functions, with the same semantics.
Moreover, there shall be additional overloads sufficient to ensure:
If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double.
Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.
Otherwise, all arguments corresponding to double parameters are effectively cast to float.
So to sum up:
long double
>> long double
float
>> float
double
Upvotes: 4
Reputation: 167
From cpp reference
7) A set of overloads or a function template for all combinations of arguments of arithmetic type not covered by 1-3). If any argument has integral type, it is cast to double. If any argument is long double, then the return type Promoted is also long double, otherwise the return type is always double.
"If any argument has integral type, it is cast to double" then it would call, converting your double to float.
float pow( float base, float exp );
Upvotes: 0