When do I use fabs and when is it sufficient to use std::abs?

后端 未结 4 2009
野趣味
野趣味 2020-12-02 17:41

I assume that abs and fabs are behaving different when using math.h. But when I use just cmath and std::abs,

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 18:44

    "abs" and "fabs" are only identical for C++ float types, when they can be translated without ambiguous overload messages.

    I'm using g++ (g++-7). Together with template usage and especially when using mpreal there are cases with hard "ambiguous overload" messages - abs(static_cast(x)) isn't always solving that. When abs is ambiguous, there are chances that fabs is working as expected. For sqrt I found no such simple escape.

    Since weeks I'm hard struggling on C++ "not existing problems". I'm updating an old C++ program to C++14 for more and better template usage than possible before. Often the same template parameter may be actual any standard float or complex type or a class type. Why ever, long double acted somewhat more sensible than other types. All was working, and I had included mpreal before. Then I was setting my default float type to mpreal and got a deluge of syntax errors. That gave thousands of ambiguous overloads e.g. for abs and sqrt, crying for different solutions. Some were needing overloaded help functions, but outside of a template. Had to replace individually a thousand usages of 0.0L and 1.0L with the exact constant type using Zero or One or a type_cast - automatic conversion definition impossible because of ambiguities.

    Up to May I found the existing of implicit conversions very nice. But much simpler it would be without any, and to have typesave constants with safe explicit type_casts to any other standard constant type.

提交回复
热议问题