I have the following simple implementation of a Heterogeneous container:
struct Container {
struct HolderBase {
};
template<typename S>
struct Holder : HolderBase {
Holder(S* s) : s_(s) {}
S* s_;
};
template<typename S>
void push_back(S* s) {
h_.push_back(new Holder<S>(s));
}
vector<HolderBase*> h_;
template<typename B>
B* get(int i) {
//magic here
}
};
Here's how to use it:
struct ElementBase {};
struct Element : ElementBase {};
int main()
{
Container container;
container.push_back(new Element);
ElementBase* elementBase = container.get<ElementBase>(0);
}
I can add entries of any type to it. But I can't figure out how to implement a function to retrieve elements, as some type, which may be the same as the entry or a base class to it.
What I need seems to be both virtual and template at the same time, which is not possible.
It doesn't seem possible to have exactly what you want without much pain and inconvenience (for example, registering all classes you want to work with in some kind of central repository).
Here's one way to do almost what you want that can perhaps be useful.
Your container is then just a
vector<unique_ptr<HolderBase>>
or whatever bunch-of-pointers you fancy.Test drive: