Golias Engine
A C++ 20 'game engine' built with SDL3 with wide platform support.
dictionary.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "str.h"
4 #include <any>
5 #include <typeindex>
6 
7 
8 class Dictionary {
10 
11 public:
12  Dictionary() = default;
13 
14  size_t size() const;
15 
16  bool is_empty() const;
17 
18  void clear();
19 
20  template <typename T>
21  void set(const String& key, const T& value) {
22  data[key] = value;
23  }
24 
25  template <typename T>
26  T get(const String& key, const T& default_value = T{}) const {
27  auto it = data.find(key);
28  if (it == data.end()) {
29  return default_value;
30  }
31 
32  try {
33  return std::any_cast<T>(it->second);
34  } catch (const std::bad_any_cast&) {
35  return default_value;
36  }
37  }
38 
39  bool has(const String& key) const;
40 
41  bool erase(const String& key);
42 
43  Vector<String> keys() const;
44 
45  template <typename T>
46  bool is_type(const String& key) const {
47  auto it = data.find(key);
48 
49  if (it == data.end()) {
50  return false;
51  }
52 
53  return it->second.type() == typeid(T);
54  }
55 
56  std::type_index get_type(const String& key) const;
57 
58  void merge(const Dictionary& other, bool overwrite = false);
59 
60  template <typename Func>
61  void for_each(Func func);
62 
63  auto begin();
64  auto end();
65  auto begin() const;
66  auto end() const;
67 };
68 
69 template <typename Func>
70 inline void Dictionary::for_each(Func func) {
71  for (auto& pair : data) {
72  func(pair.first, pair.second);
73  }
74 }
Definition: dictionary.h:8
bool is_type(const String &key) const
Definition: dictionary.h:46
size_t size() const
Definition: dictionary.cpp:4
void clear()
Definition: dictionary.cpp:12
auto end()
Definition: dictionary.cpp:54
void merge(const Dictionary &other, bool overwrite=false)
Definition: dictionary.cpp:41
std::type_index get_type(const String &key) const
Definition: dictionary.cpp:33
bool has(const String &key) const
Definition: dictionary.cpp:16
Vector< String > keys() const
Definition: dictionary.cpp:24
void for_each(Func func)
Definition: dictionary.h:70
bool is_empty() const
Definition: dictionary.cpp:8
bool erase(const String &key)
Definition: dictionary.cpp:20
void set(const String &key, const T &value)
Definition: dictionary.h:21
auto begin()
Definition: dictionary.cpp:50
Dictionary()=default
T get(const String &key, const T &default_value=T{}) const
Definition: dictionary.h:26
Definition: str.h:8
Definition: vector.h:10
std::unordered_map< K, V > HashMap
Definition: type_alias.h:20