OSSIA
Open Scenario System for Interactive Application
Loading...
Searching...
No Matches
enum_map.hpp
1#pragma once
2#include <cassert>
3#include <cinttypes>
4#include <type_traits>
5#include <utility>
6
7namespace ossia
8{
12template <typename T1, typename T2>
13struct pair
14{
15 T1 key;
16 T2 value;
17};
18
23template <typename K, typename V, std::size_t N>
25{
26 static_assert(std::is_enum_v<K>);
27
28public:
29 constexpr enum_map() = default;
30 constexpr enum_map(const enum_map&) = default;
31 constexpr enum_map(enum_map&&) noexcept = default;
32 constexpr enum_map& operator=(const enum_map&) = default;
33 constexpr enum_map& operator=(enum_map&&) noexcept = default;
34
35 constexpr explicit enum_map(std::initializer_list<pair<K, V>> i)
36 {
37 for(auto& [k, v] : i)
38 {
39 auto idx = static_cast<std::underlying_type_t<K>>(k);
40 assert(idx >= 0 && idx < int64_t(N));
41
42 m_map[idx] = std::move(v);
43 }
44 }
45
46 constexpr const V& operator[](K k) const noexcept
47 {
48 auto idx = static_cast<std::underlying_type_t<K>>(k);
49 assert(idx >= 0 && idx < int64_t(N));
50
51 return m_map[idx];
52 }
53
54 constexpr const V& operator[](int64_t idx) const noexcept
55 {
56 assert(idx >= 0 && idx < int64_t(N));
57
58 return m_map[idx];
59 }
60
61 constexpr K key(const V& v) const noexcept
62 {
63 for(std::size_t i = 0; i < N; i++)
64 {
65 if(m_map[i] == v)
66 {
67 return static_cast<K>(i);
68 }
69 }
70
71 assert(false); // key not found, hard error
72 return {};
73 }
74
75 constexpr std::optional<K> find_key(const V& v) const noexcept
76 {
77 for(std::size_t i = 0; i < N; i++)
78 {
79 if(m_map[i] == v)
80 {
81 return static_cast<K>(i);
82 }
83 }
84
85 return {};
86 }
87
88 pair<K, const V&> get(int64_t i) const noexcept
89 {
90 assert(i >= 0 && i < int64_t(N));
91 return {static_cast<K>(i), m_map[i]};
92 }
93
94 [[nodiscard]] constexpr std::size_t size() const noexcept { return N; }
95
96private:
97 V m_map[N];
98};
99}
A container useful for mapping contiguous enums to strings without using too much memory.
Definition enum_map.hpp:25
The value class.
Definition value.hpp:173
Definition git_info.h:7
A most simple pair type, to reduce binary bloat.
Definition enum_map.hpp:14