Please suggest an effective way to iterate through base classes of a container.
class Base {
public:
void bar() = 0;
};
class Derived : public Base {
public:
void bar() {}
};
class BaseContainer {
public:
virtual /*iterator to Base*/ begin() = 0;
virtual /*iterator to Base*/ end() = 0;
};
class DerivedContainer : public BaseContainer {
public:
virtual /*iterator to Base*/ begin() { ??? }
virtual /*iterator to Base*/ end() { ??? }
private:
std::vector<Derived *> m_v;
};
void use_container(BaseContainer * c) {
std::for_each(c->begin(), c->end(), [](Base * b){ b->bar(); });
}
void main() {
DerivedContainer c;
use_container(&c);
}
Commonly I do like this:
class BaseContainer {
virtual int count() = 0;
virtual Base * element(int i) = 0;
}
class DerivedContainer {
public:
virtual int count() const { return m_v.size(); }
virtual Base * element(int i) { return m_v.at(i); }
private:
std::vector<Derived *> m_v;
}
void use_container(BaseContainer * c) {
for (int i = 0; i < c->count(); i++) {
c->element(i)->bar();
}
}
But I want to use std algorithms.