-
Notifications
You must be signed in to change notification settings - Fork 8
/
enum-utils.h
83 lines (63 loc) · 1.85 KB
/
enum-utils.h
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
#pragma once
#include <concepts>
#include <limits>
#include <type_traits>
template <typename T>
concept Enum = std::is_enum_v<T>;
template <Enum E>
using PrimitiveType = std::underlying_type_t<E>;
template <Enum E>
constexpr auto sentinel_for = std::numeric_limits<PrimitiveType<E>>::max();
template <Enum E>
constexpr auto rep(E e) { return PrimitiveType<E>(e); }
template <Enum E>
constexpr E operator&(E a, E b) { return E(rep(a) & rep(b)); }
template <Enum E>
constexpr E operator|(E a, E b) { return E(rep(a) | rep(b)); }
template <Enum E>
constexpr E& operator&=(E& a, E b) { return a = a & b; }
template <Enum E>
constexpr E& operator|=(E& a, E b) { return a = a | b; }
template <Enum E>
constexpr auto retract(E e, PrimitiveType<E> x = 1) { return E(rep(e) - x); }
template <Enum E>
constexpr auto extend(E e, PrimitiveType<E> x = 1) { return E(rep(e) + x); }
template <Enum E>
constexpr bool implies(E a, E b) { return (a & b) == b; }
template <Enum E>
constexpr E unit = { };
template <typename E>
concept YesNoEnum = Enum<E>
&& std::same_as<PrimitiveType<E>, bool>
&& requires {
{ E::Yes };
{ E::No };
}
&& rep(E::Yes) == true
&& rep(E::No) == false;
template <YesNoEnum E>
constexpr bool is_yes(E e)
{
return rep(e);
}
template <YesNoEnum E>
constexpr bool is_no(E e)
{
return not rep(e);
}
template <YesNoEnum T>
constexpr T make_yes_no(bool value) noexcept
{
return static_cast<T>(value);
}
template <typename T>
concept Countable = requires(T) {
T::Count;
};
template <Countable T>
constexpr bool last_of(T t)
{
return extend(t) == T::Count;
}
template <Countable T>
constexpr auto count_of = rep(T::Count);