engine/include/resource_manager.hpp

48 lines
1023 B
C++
Raw Normal View History

2022-09-02 11:06:59 +00:00
#pragma once
#include <unordered_map>
2022-12-01 15:54:28 +00:00
#include <string>
#include <memory>
#include <stdexcept>
2022-09-02 11:06:59 +00:00
2022-10-06 10:30:44 +00:00
namespace engine {
2022-09-02 11:06:59 +00:00
2022-12-01 15:54:28 +00:00
template <class T>
class ResourceManager {
2022-09-02 11:06:59 +00:00
2022-10-06 10:30:44 +00:00
public:
2022-12-01 15:54:28 +00:00
ResourceManager() {}
2022-12-15 10:07:22 +00:00
~ResourceManager() {}
2022-10-06 10:30:44 +00:00
ResourceManager(const ResourceManager&) = delete;
ResourceManager& operator=(const ResourceManager&) = delete;
2022-09-02 11:06:59 +00:00
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> add(const std::string& name, std::unique_ptr<T>&& resource)
2022-12-01 15:54:28 +00:00
{
if (m_resources.contains(name) == false) {
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> resourceSharedPtr(std::move(resource));
m_resources.emplace(name, resourceSharedPtr);
return resourceSharedPtr;
2022-09-02 11:06:59 +00:00
}
else {
2022-12-01 15:54:28 +00:00
throw std::runtime_error("Cannot add a resource which already exists");
2022-09-02 11:06:59 +00:00
}
2022-12-01 15:54:28 +00:00
}
2022-10-06 10:30:44 +00:00
2022-12-20 23:51:04 +00:00
std::shared_ptr<T> get(const std::string& name)
2022-12-01 15:54:28 +00:00
{
if (m_resources.contains(name)) {
2022-12-20 23:51:04 +00:00
std::weak_ptr<T> ptr = m_resources.at(name);
if (ptr.expired() == false) {
return ptr.lock();
}
2022-12-01 15:54:28 +00:00
}
return {};
2022-09-02 11:06:59 +00:00
}
2022-10-06 10:30:44 +00:00
2022-12-01 15:54:28 +00:00
private:
2022-12-20 23:51:04 +00:00
std::unordered_map<std::string, std::weak_ptr<T>> m_resources{};
2022-09-02 11:06:59 +00:00
2022-12-01 15:54:28 +00:00
};
2022-09-02 11:06:59 +00:00
2022-12-15 10:07:22 +00:00
}