WHY_CPP  0.1
context.h
1 #pragma once
2 
3 #include <memory>
4 #include <typeindex>
5 #include <unordered_map>
6 #include <utility>
7 #include "logger.h"
8 
9 class IObject;
26 class Context {
27  std::unordered_map<std::type_index, std::unique_ptr<IObject>> memory;
28 
29  public:
30  Context() {
31  LOG_DEBUG("Context created");
32  }
33  virtual ~Context() {
34  LOG_DEBUG("Context destroyed");
35  }
36  template<typename TObject, typename... Args>
37  TObject* Put(Args&&... args) {
38  memory[typeid(TObject)] = std::make_unique<TObject>(std::forward<Args>(args)...);
39  return Get<TObject>();
40  }
41 
42  template<typename TObject, typename TAsObject, typename... Args>
43  TAsObject* PutAs(Args&&... args) {
44  memory[typeid(TAsObject)] = std::make_unique<TObject>(std::forward<Args>(args)...);
45  return Get<TAsObject>();
46  }
47 
48  template<typename TObject>
49  TObject* Get() const {
50  if (memory.count(typeid(TObject)) == 0) {
51  LOG_ERROR("<%s> not found in the Container", typeid(TObject).name());
52  return nullptr;
53  }
54  return dynamic_cast<TObject*>(memory.at(typeid(TObject)).get());
55  }
56 };
57