NasNas
An intuitive and beginner friendly 2D game framework for C++
PropertiesContainer.hpp
1 
6 #pragma once
7 
8 #include <iostream>
9 #include <string>
10 #include <type_traits>
11 #include <unordered_map>
12 #include <variant>
13 
14 #include <SFML/Graphics/Color.hpp>
15 
16 namespace pugi {
17  class xml_node;
18 }
19 
20 namespace ns::tm {
21 
22  using PropertyTypes = std::variant<int, float, std::string, bool, sf::Color>;
23 
24  auto hexToColor(const std::string& color_string) -> sf::Color;
25 
27  public:
29 
30  auto hasProperty(const std::string& name) const -> bool;
31 
32  template <typename T>
33  auto getProperty(const std::string& name) const -> const T&;
34 
35  template <typename T>
36  void addProperty(const std::string& name, const T& value);
37 
38  void printProperties() const;
39 
40  protected:
41  void parseProperties(const pugi::xml_node& xmlnode_props);
42 
43  private:
44  std::unordered_map<std::string, PropertyTypes> m_properties;
45 
46  };
47 
48  template<typename T>
49  auto PropertiesContainer::getProperty(const std::string& name) const -> const T& {
50  if (m_properties.count(name)) {
51  if (std::holds_alternative<T>(m_properties.at(name))) {
52  return std::get<T>(m_properties.at(name));
53  }
54  std::cout << "Error (bad_variant_access) : Property «" << name
55  << "» is not of type " << typeid(T).name()
56  << ". You are requesting the wrong type." << std::endl;
57  exit(-1);
58  }
59  std::cout << "Error : Property named «" << name << "» does not exist." << std::endl;
60  exit(-1);
61  }
62 
63  template<typename T>
64  void PropertiesContainer::addProperty(const std::string& name, const T& value) {
65  if (std::is_same_v<int, T> || std::is_same_v<float, T> || std::is_same_v<bool, T> ||
66  std::is_same_v<std::string, T> || std::is_same_v<sf::Color, T>) {
67  m_properties[name] = value;
68  }
69  else {
70  std::cout << "Error : Cannot add property of type " << typeid(T).name()
71  << ". (Accepted types are int, float, bool, std::string, sf::Color)."<< std::endl;
72  exit(-1);
73  }
74  }
75 
76 }