abs.hpp 2.2 KB

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