I want to create a templated API to access derived types that are stored in a vector of vectors. The outer vector has an element for each derived type. The inner vector has a collection of those types.
std::vector<std::vector<MyBaseClass>* > items;
Ideally, I would like to provide an API where derived types of MyBaseClass can be added and accessed (without specialized templates). Something like this:
T& addItem(size_t index, T& item);
T& getItem(size_t index);
Use like this:
AClass : public MyBaseClass {};
BClass : public MyBaseClass {};
addItem<AClass&>(123, item);
addItem<BClass&>(456, item);
AClass& = getItem<AClass&>(123);
BClass& = getItem<BClass&>(456);
The reason for the lack of specialized templates is that I want to enable the use of new derived types without other developers having to modify this code.
So, is there a way I can get this kind of API implemented without having to know the derived class types and specialize the code?
Is it possible to do this with a union and template?
Note: The inner vector needs to store its data consecutively in memory, so I am not using pointers.
Note: I am using C++11 without Boost.
Thanks.