Blame view

3rdparty/boost_1_81_0/boost/math/ccmath/abs.hpp 2.16 KB
63e88f80   Hu Chunming   提交三方库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  //  (C) Copyright Matt Borland 2021.
  //  Use, modification and distribution are subject to the
  //  Boost Software License, Version 1.0. (See accompanying file
  //  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  //
  //  Constepxr implementation of abs (see c.math.abs secion 26.8.2 of the ISO standard)
  
  #ifndef BOOST_MATH_CCMATH_ABS
  #define BOOST_MATH_CCMATH_ABS
  
  #include <cmath>
  #include <type_traits>
  #include <limits>
  #include <boost/math/tools/is_constant_evaluated.hpp>
  #include <boost/math/tools/assert.hpp>
  #include <boost/math/ccmath/isnan.hpp>
  #include <boost/math/ccmath/isinf.hpp>
  
  namespace boost::math::ccmath {
  
  namespace detail {
  
  template <typename T> 
  constexpr T abs_impl(T x) noexcept
  {
      if (boost::math::ccmath::isnan(x))
      {
          return std::numeric_limits<T>::quiet_NaN();
      }
      else if (x == static_cast<T>(-0))
      {
          return static_cast<T>(0);
      }
  
      if constexpr (std::is_integral_v<T>)
      {
          BOOST_MATH_ASSERT(x != (std::numeric_limits<T>::min)());
      }
      
      return x >= 0 ? x : -x;
  }
  
  } // Namespace detail
  
  template <typename T, std::enable_if_t<!std::is_unsigned_v<T>, bool> = true>
  constexpr T abs(T x) noexcept
  {
      if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))
      {
          return detail::abs_impl<T>(x);
      }
      else
      {
          using std::abs;
          return abs(x);
      }
  }
  
  // If abs() is called with an argument of type X for which is_unsigned_v<X> is true and if X
  // cannot be converted to int by integral promotion (7.3.7), the program is ill-formed.
  template <typename T, std::enable_if_t<std::is_unsigned_v<T>, bool> = true>
  constexpr T abs(T x) noexcept
  {
      if constexpr (std::is_convertible_v<T, int>)
      {
          return detail::abs_impl<int>(static_cast<int>(x));
      }
      else
      {
          static_assert(sizeof(T) == 0, "Taking the absolute value of an unsigned value not covertible to int is UB.");
          return T(0); // Unreachable, but suppresses warnings
      }
  }
  
  constexpr long int labs(long int j) noexcept
  {
      return boost::math::ccmath::abs(j);
  }
  
  constexpr long long int llabs(long long int j) noexcept
  {
      return boost::math::ccmath::abs(j);
  }
  
  } // Namespaces
  
  #endif // BOOST_MATH_CCMATH_ABS