Rationale for cmath's std::abs(short) -> double

Jonathan Wakely jwakely.gcc@gmail.com
Wed Feb 3 10:57:00 GMT 2016


On 3 February 2016 at 10:25, Stephan Bergmann <sbergman@redhat.com> wrote:
> I once again wonder why
> <https://gcc.gnu.org/viewcvs/gcc?view=revision&revision=150022> added that
>
>> template<typename _Tp> typename
>> __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type abs(_Tp)
>
>
> overload to cmath, causing a call to std::abs with an argument of type short
> to return a double, even if cstdlib is also included (which declares the
> int, long, long long overloads).  That commit does not give any rationale.
>
> (I apparently wondered about that already a couple of years ago, but all I
> can find now in my notes is "[...] only to discover libstdc++'s over-eager
> interpretation of C++11 cmath requirements causes std::abs with a short
> argument to chose the double overload," which no longer rings much of a bell
> with me.)
>
> This issue happens to crop up again now in the context of the LibreOffice
> code base, see <https://gerrit.libreoffice.org/#/c/22050/> "Make abs return
> int, not double," which reportedly is on Fedora Rawhide.

The dreaded "sufficient additional overloads" required by [c.math] p11

2. Otherwise, if any argument of arithmetic type corresponding to a
double parameter has type double
or an integer type, then all arguments of arithmetic type
corresponding to double parameters are
effectively cast to double.

That means that the <cmath> functions should be overloaded so that
non-floating point arguments are promoted to double.

abs is an oddity though, as it also has integral overloads. The
proposed resolution for http://wg21.link/lwg2192 suggests it should
promote to int, although it's not entirely clear.



More information about the Libstdc++ mailing list