qxLib
between.inl
Go to the documentation of this file.
1 /**
2 
3  @file between.inl
4  @author Khrapov
5  @date 25.09.2025
6  @copyright © Nick Khrapov, 2025. All right reserved.
7 
8 **/
9 
10 namespace qx
11 {
12 
13 // trick to determine if an integer is between two integers (inclusive)
14 // with only one comparison/branch
15 // https://stackoverflow.com/a/17095534/8021662
16 QX_DISABLE_MSVC_WARNINGS(4018 4388);
17 
18 template<class T, class compare_t>
19 constexpr bool between(T left, T value, T right, compare_t compare)
20 {
21  if constexpr (std::is_enum_v<T>)
22  {
23  i64 l = static_cast<i64>(left);
24  i64 r = static_cast<i64>(right);
25  i64 v = static_cast<i64>(value);
26  return between(l, v, r, compare);
27  }
28  else if constexpr (std::is_integral_v<T> && std::is_same_v<compare_t, std::less_equal<>>)
29  {
30  return compare(static_cast<size_t>(value - left), right - left);
31  }
32  else if constexpr (std::is_floating_point_v<T> && std::is_same_v<compare_t, std::less_equal<>>)
33  {
34  return epsilon_less_equal(left, value) && epsilon_less_equal(value, right);
35  }
36  else
37  {
38  return compare(left, value) && compare(value, right);
39  }
40 }
41 
42 template<class T, class compare_t>
43 constexpr bool between(T left, T value, T right)
44 {
45  QX_PUSH_SUPPRESS_MSVC_WARNINGS(4388);
46  return between(left, value, right, compare_t());
47  QX_POP_SUPPRESS_WARNINGS();
48 }
49 
50 QX_RESTORE_MSVC_WARNINGS(4018 4388);
51 
52 } // namespace qx
constexpr bool between(T left, T value, T right)
Checks if value is between left and right.
Definition: between.inl:43
constexpr bool epsilon_less_equal(T left, T right, T eps=std::numeric_limits< T >::epsilon())
Constexpr comparison function for a user defined epsilon values.