On the std::abs function

只谈情不闲聊 提交于 2019-12-02 22:23:18

The correct overloads are guaranteed to be present in <cmath>/<cstdlib>:

C++11, [c.math]:

In addition to the int versions of certain math functions in <cstdlib>, C++ adds long and long long overloaded versions of these functions, with the same semantics.

The added signatures are:

long abs(long);            // labs()
long long abs(long long);  // llabs()

[...]

In addition to the double versions of the math functions in <cmath>, overloaded versions of these functions, with the same semantics. C++ adds float and long double overloaded versions of these functions, with the same semantics.

float abs(float);
long double abs(long double);

So you should just make sure to include correctly <cstdlib> (int, long, long long overloads)/<cmath> (double, float, long double overloads).

You cannot guarantee that std::abs(x) will always return |x| for all arithmetic types. For example, most signed integer implementations have room for one more negative number than positive number, so the results of abs(numeric_limits<int>::min()) will not equal |x|.

Check that you're in fact using std::abs from <cstdlib> and not std::abs from <cmath>.

PS. Oh, just saw the example program, well, there you go, you are using one of the floating point overloads of std::abs .

It's not weird that g++ (with C++11 standard) returns a double when you use std::abs from <cmath> with an integral type: From http://www.cplusplus.com/reference/cmath/abs/:

Since C++11, additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type).

This is actually implemented like that in /usr/include/c++/cmath:

template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
                                double>::__type
abs(_Tp __x)
{ return __builtin_fabs(__x); }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!