Hey all,
This is a little contrived, but say I have a class interface like this:
class IResource;
class IResourceContainer
{
public:
virtual ~IResourceContainer() {}
virtual void AddResource(const std::string& rStrName,
std::auto_ptr<IResource> apResource)=0;
virtual IResource& GetResource(const std::string& rStrName)=0;
};
and I have an implementation of this class which contains a map of strings to IResource types. If I were to add my own resource like this:
container.AddResource("foo", std:auto_ptr<IResource>( new CFooResource);
and then later retrieve the resource reference
CFooResource& fooResource = container.GetResource(); // error
This wouldn't compile since I would need to downcast the IResource to a CFooResource. I thought about hiding this by making GetResource take a template parameter which downcasts the type internally, but obviously, templates and pure interfaces don't jive. My current alternative is to hide the casting in a CastResource function which calls boost::polymorphic_downcast, but I'm still not thrilled with the idea that a client will need to cast the resource.
For example:
CFooResource& fooResource = CastResource<CFooResource&>(container.GetResource());
So I guess my question is: is there a better way of holding pointers to generic types that don't require explicit downcasts from the user? I feel like there's a templated way of doing this, but I'm not seeing it. Also, I made this interface so that clients could easily mock it out in their tests if need be.
Thanks.