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.
std::vector
withstd::any
(or Boost any)? Or perhaps do a redesign so you don't need to use heterogeneous containers or type-erasure? – Pandemoniumany
can not do that. Anany_cast
can only cast to the actual type. Not to a base type. – Margerymarget