GameKit  0.0.1a
C++ gamedev tools
ResourceHandler.hpp
Go to the documentation of this file.
1 /*
2  * =====================================================================================
3  *
4  * Filename: ResourceHandler.hpp
5  *
6  * Description:
7  *
8  * Created: 17/01/2018 19:16:19
9  *
10  * Author: Quentin Bazin, <quent42340@gmail.com>
11  *
12  * =====================================================================================
13  */
14 #ifndef GK_RESOURCEHANDLER_HPP_
15 #define GK_RESOURCEHANDLER_HPP_
16 
17 #include <map>
18 #include <memory>
19 
20 #include "gk/core/XMLFile.hpp"
22 #include "gk/core/Exception.hpp"
23 
24 namespace gk {
25 
27  public:
28  template<typename T, typename... Args>
29  T &add(const std::string &name, Args &&...args) {
30  if(has(name)) {
31  throw EXCEPTION("A resource of type", typeid(T).name(), "already exists with name:", name);
32  }
33 
34  m_resources.emplace(name, std::make_shared<T>(std::forward<Args>(args)...));
35 
36  return get<T>(name);
37  }
38 
39  bool has(const std::string &name) {
40  return m_resources.count(name) == 1;
41  }
42 
43  template<typename T>
44  T &get(const std::string &name) {
45  auto it = m_resources.find(name);
46  if(it == m_resources.end()) {
47  throw EXCEPTION("Unable to find resource with name:", name);
48  }
49 
50  return *std::static_pointer_cast<T>(it->second);
51  }
52 
53  template<typename ResourceLoader>
54  static auto loadConfigFile(const char *xmlFilename) -> typename std::enable_if<std::is_base_of<IResourceLoader, ResourceLoader>::value>::type {
55  ResourceLoader loader;
56  loader.load(xmlFilename, getInstance());
57  }
58 
59  static ResourceHandler &getInstance();
60 
61  static void setInstance(ResourceHandler &handler);
62 
63  private:
65 
66  std::map<std::string, std::shared_ptr<void>> m_resources;
67 };
68 
69 } // namespace gk
70 
71 #endif // GK_RESOURCEHANDLER_HPP_
static ResourceHandler & getInstance()
T & add(const std::string &name, Args &&...args)
std::map< std::string, std::shared_ptr< void > > m_resources
static auto loadConfigFile(const char *xmlFilename) -> typename std::enable_if< std::is_base_of< IResourceLoader, ResourceLoader >::value >::type
#define EXCEPTION(args...)
Definition: Exception.hpp:22
static ResourceHandler * instance
bool has(const std::string &name)
static void setInstance(ResourceHandler &handler)