15 #ifndef ALLIUM_UTIL_NUMERIC_HPP
16 #define ALLIUM_UTIL_NUMERIC_HPP
19 #include "warnings.hpp"
23 template <
typename T>
struct real_part {};
24 template <>
struct real_part<float> {
typedef float type; };
25 template <>
struct real_part<double> {
typedef double type; };
26 template <>
struct real_part<int> {
typedef int type; };
27 template <>
struct real_part<long> {
typedef long type; };
28 template <
typename T>
struct real_part<std::complex<T>> {
typedef T type; };
31 template <
typename N>
struct is_complex :
public std::false_type {};
32 template <
typename N>
struct is_complex<std::complex<N>> :
public std::true_type {};
36 using real_part_t =
typename real_part<T>::type;
45 template <
typename To,
typename From,
typename Enabled =
void>
51 float operator() (
double x) {
return x; }
55 struct narrow_number<T, T> {
56 T operator() (T x) {
return x; }
60 struct narrow_number<std::complex<float>, std::complex<double>> {
61 std::complex<float> operator() (std::complex<double> x) {
62 return std::complex<float>(x.real(), x.imag());
66 template <
typename To,
typename From>
67 struct narrow_number<To, std::complex<From>,
68 std::enable_if_t<std::is_floating_point<To>::value>>
70 To operator() (std::complex<From> x) {
71 allium_assert(x.imag() == 0);
72 return narrow_number<To, From>()(x.real());
81 template <
typename T1,
typename T2>
82 std::enable_if_t<std::is_signed<T1>::value && std::is_unsigned<T2>::value,
bool>
85 return (a < 0) || (
static_cast<std::make_unsigned_t<T1>
>(a) <= b);
87 template <
typename T1,
typename T2>
88 std::enable_if_t<std::is_unsigned<T1>::value && std::is_signed<T2>::value,
bool>
91 return (b >= 0) && (a <= static_cast<std::make_unsigned_t<T2>>(b));
93 template <
typename T1,
typename T2>
94 std::enable_if_t<std::is_signed<T1>::value == std::is_signed<T2>::value,
bool>
104 template <
typename T1,
typename T2>
105 bool safe_ge(T1 a, T2 b) {
106 return safe_le(b, a);
113 template <
typename T1,
typename T2>
114 std::enable_if_t<std::is_signed<T1>::value && std::is_unsigned<T2>::value,
bool>
115 safe_lt(T1 a, T2 b) {
117 return (a < 0) || (
static_cast<std::make_unsigned_t<T1>
>(a) < b);
119 template <
typename T1,
typename T2>
120 std::enable_if_t<std::is_unsigned<T1>::value && std::is_signed<T2>::value,
bool>
121 safe_lt(T1 a, T2 b) {
123 return (b >= 0) && (a < static_cast<std::make_unsigned_t<T2>>(b));
125 template <
typename T1,
typename T2>
126 std::enable_if_t<std::is_signed<T1>::value == std::is_signed<T2>::value,
bool>
127 safe_lt(T1 a, T2 b) {
136 template <
typename T1,
typename T2>
137 bool safe_gt(T1 a, T2 b) {
138 return safe_lt(b, a);
Narrows a number type, which can result in a loss of information or accuracy.
Definition: numeric.hpp:46