(I tried searching, but you just get a flood of plain singleton explanations.)
A "normal" singleton guarantees that only one object of a given type exists in the entire program. For example, like this:
template <class T>
T& getSingleton()
{
static T instance;
return instance;
}
I am looking for a way to have no more than one object of a given type T in any given object of type O. That is, something like this:
class O
{
// getSingleton<SomeType>() always returns the same SomeType reference for the same instance of O.
// getSingleton<SomeType>() returns different SomeType references for different instances of O.
template<class T>
T& getSingleton() { /* ??? */ }
};
It is totally fine if all T are required to derive from a certain base class (which is probably required for storing them type-erased in a container inside O), say, TBase. However, the set of T we care about is open (i.e. not known at the point where O is defined), hence member variables are not a solution.
There is of course the more or less straightforward solution of storing e.g. a std::vector<std::unique_ptr<TBase>> and implementing getSingleton<T> by attempting a dynamic_cast on each element. But I wonder if there is a more elegant approach that does not take linear time.