I am trying to make a resource loader, and wish to have a class resource and a template class resource manager. Different types of resources inherit from the base resource class, for example a image, 3d mesh etc.
I could have a map for any type of resource, but then I will be unable to call functions specific to a derived class. A 3dMesh might have getVertecies() where as a image might have getWidth() etc.
Because of that I was going to use a templated resourceManager class.
Then you could create resource managers like:
The resource manager would return a pointer of the resource type rather than the base resource class. That way you could call functions specific to each resource type.
However, using this approach, you could pass in anything to make a resource manager of.
This would be fine, except the resource manager should be able to call functions of the base resource class. For example, the base resource class would have a virtual function for loading from a file, but the resource manager would be unable to call those functions as it could be passed anything as a template, and an int or string or whatever doesnt have loadFromFile().
I was thinking of doing something with template specilaisation with the base class, but then it would return pointers of the base class and not the derived ones, unless I specialised it for every single derived class, but then I may as well not have a templated class, but instead just have a resource manager class for each type.
So, is there any way of using templates and having the advantage of calling functions of derived classes, while still getting acsess to functions of the base class?
If you expect all of the types given to you to have "loadFromFile()" method than just use this method in your template. If someone will give you as a template argument "int" it won't compile, which as far as I can understand is OK, this someone is not supposed to do that.
Just document the interface you expect all the types given to you to have (e.g. "have a loadFromFile() method").
Yes, it is possible to constrain template parameters to descendants of a specific class. see this answer.
Or you could just leave it be. The resource manager will fail to compile anyway with template parameters not satisfying the needed interface.