I have a template class Foo that has a method, barMethod, that requires a Bar object. I could have each individual Foo object create Bar objects as needed, but I don't want to do that because it will be slow, and there is a good chance that different Foo objects could use the same Bar object.
Given that, I would like to have a BarManager object that has the existing set of Bar objects. The Foo objects could then ask it for Bar objects, and if an appropriate one already exists, the manager would simply return it. If it doesn't the manager would create a new one and return it.
It seems to me that there are two problems with implementing the "manager" approach.
- The manager would have to be a global variable, which I would prefer not to do.
BarManagerandBarare both template classes, so even if I were to make the manager a global variable/object, I'm not sure how that would work. I guess I could make the global variable a void * and cast it whenever it is de-referenced to the appropriate templated class, but that seems really ugly.
There has to be a way to do this that isn't so ugly (perhaps using an auto pointer?). What is it?
EDIT: This software is part of a library that I (and perhaps others) will use later, which is why the classes are templated and the template type is not known a priori. Also, I want to keep things as simple as possible for the user of Foo, so I do not want the caller to have to do anything with BarManager or Bar (e.g. instantiating BarManager and giving the reference to each Foo).