fork(1) download
  1. #include <memory>
  2. #include <unordered_map>
  3.  
  4. class Resource {
  5. public:
  6. Resource(const std::string&) {}
  7. virtual ~Resource() {}
  8. };
  9.  
  10. class Texture : public Resource {
  11. public:
  12. int width;
  13. int height;
  14. int channels;
  15. uint8_t* data;
  16.  
  17. Texture(const std::string& path) : Resource(path) {
  18. load(path);
  19. }
  20.  
  21. virtual ~Texture() {
  22. // if needed for whatever reason
  23. unload();
  24. }
  25. protected:
  26. void load(const std::string& path) {
  27. // loading logic in here
  28. }
  29.  
  30. void unload() {
  31. // unloading logic in here
  32. }
  33. };
  34.  
  35. class ResourceManager {
  36. public:
  37. template<typename T>
  38. std::shared_ptr<T> load(const std::string& path) {
  39. static_assert(std::is_base_of<Resource, T>::value, "T must inherit from Resource");
  40.  
  41. auto res = resources[path].lock();
  42. if(!res) {
  43. // assuming constructor loads resource
  44. resources[path] = res = std::make_shared<T>(path);
  45. }
  46.  
  47. auto return_value = std::dynamic_pointer_cast<T>(res);
  48. if(!return_value) {
  49. throw std::runtime_error(std::string("Resource '") + path + "' is already loaded as another type");
  50. }
  51. return return_value;
  52. }
  53. private:
  54. std::unordered_map<std::string, std::weak_ptr<Resource>> resources;
  55. };
  56.  
  57. int main() {
  58. ResourceManager man;
  59. auto tex = man.load<Texture>("path");
  60. }
Success #stdin #stdout 0s 16072KB
stdin
Standard input is empty
stdout
Standard output is empty