I'm working on an asset manager for my game engine, and I'm a bit stumped on how to use templates (and potentially inheritance) to reduce some code duplication.
An asset requires 4 things: a container, load function, and two getters. So for 4 assets (e.g Mesh, Texture, Shader, Audio) that's 16 things to add to the code, which looks like this:
namespace ResourceManager {
namespace {
std::unordered_map<ResourceHandle, MeshMeta> meshes;
std::unordered_map<ResourceHandle, TextureMeta> textures;
std::unordered_map<ResourceHandle, ShaderMeta> shaders;
}
void ReloadResources() {}
ResourceHandle LoadMesh() {}
MeshMeta GetMesh(ResourceHandle handle) {}
ResourceHandle GetMesh(const std::string& filepath) {}
ResourceHandle LoadTexture() {}
TextureMeta GetTexture(ResourceHandle handle) {}
ResourceHandle GetTexture(const std::string& filepath) {}
ResourceHandle LoadShader() {}
ShaderMeta GetShader(ResourceHandle handle) {}
ResourceHandle GetShader(const std::string& filepath) {}
}
Although the code is fine as is, I don't think it's right to leave it like this. I don't think there's anything I can do about the load functions, but the getters I can probably avoid duplicating by using templates, since all they do is search a map using the handle.
So my ideal code would look something like this:
namespace ResourceManager {
namespace {
std::unordered_map<ResourceHandle, MeshMeta> resources;
}
void ReloadResources() {}
ResourceHandle LoadMesh() {}
ResourceHandle LoadTexture() {}
ResourceHandle LoadShader() {}
ResourceMeta GetResource(ResourceHandle handle) {}
ResourceHandle GetResource(const std::string& filepath) {}
}
I feel this is a much more sane approach, but I don't know how I'd use templates to achieve only 2 getters and a single resource map.