Take the following "type" dictionary -- its keys are supposed to be types, and values an instance of that type:
class TypeDictionary {
public:
template<class T> void insert(T t);
template<class T> T& get();
// implementation be here -- and the question is about this
};
struct Foo;
struct Bar;
void userOfTypeDictionary() {
TypeDictionary td;
td.insert( Foo() );
td.insert( Bar() );
td.insert( double(3.14) );
// and other unknown (to TypeDictionary)
// list of types attached
// later on, in a different scope perhaps
Foo& f = td.get<Foo>() ;
Bar& f = td.get<Bar>();
double pi = tg.get<double>();
// ...
}
This particular TypeDictionary has a growing set of types "registered", but of course, the facility should allow an arbitrary set of types, and potentially a different set for each instance of this class.
As for a realistic motivating use case, think of a plugin manager. At any given time of its life an arbitrary heterogeneous set of objects are attached to it, and the it is the manager's job to manage the life time of the attached objects and return (a reference) to them when queried in a type-safe manner.
Any ideas on whether such a thing is possible? It is fine if a strategy involves using a library, like Boost.Fusion or similar.