I am writing a game and I use a ResourceHolder template class which provides functions to load and access a resource(texture, music, font...). It works great for Texture or Font classes because they have the same interface for loading(their functions are called "loadFromFile") but the Music class works a bit differently and it has an "openFromFile" function instead (I use a library called SFML).
template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::load(Identifier id,
const std::string & fileName)
{
std::unique_ptr<Resource> resource(new Resource());
resource->loadFromFile(fileName);
}
I tried an if-else approach:
if (typeid(id).name() == "Resources::MusicType")
resource->openFromFile(fileName);
else
resource->loadFromFile(fileName);
But compiler throws an error when compiling the Texture version of the template since it doesn't have openFromFile method. I also considered passing the function as a third template parameter but I'd like to know whether there is a better solution. Thanks.
Template Specialization is your friend.
Basically you can create a specialized function for specific types:
template <typename Resource>
void ResourceHolder<Resource, MusicType>::load(...)
I'm not sure this is the right way, as I'm not sure what's the difference between Resource
and Identifier
, and how you use them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments