How do you check for infinite and indeterminate values in C++?

前端 未结 6 2102
借酒劲吻你
借酒劲吻你 2020-12-29 20:31

In my programs infinity usually arises when a value is divided by zero. I get indeterminate when I divide zero by zero. How do you check for infinite and indeterminate value

6条回答
  •  臣服心动
    2020-12-29 21:24

    You may also use these as a strict C++-only solution. They don't really offer more than the OP's solution except added security through use of type traits and perhaps the tiniest speed boost in the case of is_inf.

    template  struct static_assert;
    template <> struct static_assert { };
    
    template
    inline bool is_NaN(T const& x) {
        static_cast(sizeof(static_assert::has_quiet_NaN>));
        return std::numeric_limits::has_quiet_NaN and (x != x);
    }
    
    template 
    inline bool is_inf(T const& x) {
        static_cast(sizeof(static_assert::has_infinity>));
        return x == std::numeric_limits::infinity() or x == -std::numeric_limits::infinity();
    }
    

    (beware of self-made static_assert)

提交回复
热议问题