SAT Solver Template
Loading...
Searching...
No Matches
enum.hpp
Go to the documentation of this file.
1/**
2* @author Tim Luchterhand
3* @date 04.10.24
4* @file enum.hpp
5* @brief enum utilities
6*/
7
8#ifndef ENUM_HPP
9#define ENUM_HPP
10
11#include <ostream>
12#include <array>
13#include <ranges>
14#include <type_traits>
15#include <string_view>
16
17/**
18 * Converts enum to underlying type
19 * @tparam E enum type
20 * @param e enum to convert
21 * @return value of underlying type
22 * @note replace with std impl in c++23: https://en.cppreference.com/w/cpp/utility/to_underlying
23 */
24template<typename E>
25constexpr auto to_underlying(E e) noexcept {
26 return static_cast<std::underlying_type_t<E>>(e);
27}
28
29namespace enum_detail {
30 template<const std::string_view &String, char Delim>
31 class split {
32 static consteval auto numParts() {
33 unsigned ret = 1;
34 for (char c: String) {
35 ret += (c == Delim);
36 }
37
38 return ret;
39 }
40
41 static consteval auto extractString(auto begin, auto end) {
42 auto str = std::ranges::subrange(begin, end) |
43 std::views::drop_while([](char c) { return c == ' '; });
44 return std::string_view(str.begin(), str.end());
45 }
46
47 static consteval auto doSplit() {
48 std::array<std::string_view, numParts()> ret;
49 auto start = String.begin();
50 std::size_t arrayIdx = 0;
51 for (auto curr = String.begin(); curr != String.end(); ++curr) {
52 if (*curr == Delim) {
53 ret[arrayIdx++] = extractString(start, curr);
54 start = curr + 1;
55 }
56 }
57
58 ret[arrayIdx] = extractString(start, String.end());
59 return ret;
60 }
61
62 public:
63 static constexpr auto value = doSplit();
64 };
65}
66
67/**
68 * @brief Create a printable enum class
69 * @details specify the enum class name first and then an arbitrary number of entries.
70 * @param NAME enum class name
71 * @param VA_ARGS arbitrary number of enum entries
72 */
73#define PENUM(NAME, ...) enum class NAME { __VA_ARGS__ }; inline
74 constexpr std::string_view __##NAME##_enum_str_vals__ = #__VA_ARGS__; inline
75 constexpr std::array __##NAME##_converter__{enum_detail::split<__##NAME##_enum_str_vals__, ','>::value };inline
76 std::ostream &operator<<(std::ostream &os, NAME e) {
77 os << __##NAME##_converter__.at(to_underlying(e));
78 return os; \
79} inline
80 auto to_string(NAME e) {
81 return std::string(__##NAME##_converter__.at(to_underlying(e))); \
82}
83
84#endif //TEMPO_ENUM_HPP
Definition enum.hpp:31
constexpr auto to_underlying(E e) noexcept
Definition enum.hpp:25