I've implemented a template-based resource management system based on the ideas mentioned by rip-off (here and here). It uses template specialisation, which I haven't used before, so I was hoping some could confirm whether what I've done is reasonable (or not).
The system uses a template class called ResourceLoader, which is used by a separate cache (also a template) to load and instantiate resource objects. Because each resource type needs different data (and parameters) to construct, I've created specialised loader classes for each type.
// Used to read the actual resource file bytes from an archive/wherever.
class ResourceLocator;
template<typename T>
class ResourceLoader
{
public:
ResourceLoader(const ResourceLocator *locator) : _locator(locator) {}
private:
ResourceLocator* _locator;
};
// Simple example: vertex shader loader.
class VertexShader;
template<>
class ResourceLoader<VertexShader>
{
public:
// Load the named vertex shader.
std::shared_ptr<VertexShader> load(const std::string& name)
{
// Read the shader source from disk (doesn't matter how).
std::vector<char> buffer;
_locator->read(name, buffer);
// Construct the shader, passing it's source code as a parameter.
std::string shaderSource(buffer.begin(), buffer.end());
return std::make_shared<VertexShader>(shaderSource);
}
};
Each resource type needs to be loaded in a different way, so I don't have a truly generic load() method in the ResourceLoader class itself - which I think is the correct way of doing this, although it seems a little odd.
Seem reasonable?
Thanks for any advice. Cheers!