将迭代器返回给基类

时间:2013-10-14 00:48:32

标签: c++ containers

请建议一种有效的方法来迭代容器的基类。

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);
}

通常我喜欢这样:

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();
  }
}

但我想使用标准算法。

0 个答案:

没有答案