我有以下类(class)

class Parent {
  virtual void doStuff() = 0;
};

class Child : public Parent {
  void doStuff() {
    // Some computation here
  }
};

我有一个具有以下签名的功能。
void computeStuff(std::vector<boost::shared_ptr<Parent> >);

只要我可以重构代码(包括函数签名),最好的方法是将函数computeStuff传递给Child对象的指针列表?

本质上,我希望以下代码片段可以编译和运行
std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds);

最佳答案

“最佳”方法是让函数采用一对迭代器:

template <typename ForwardIterator>
void computeStuff(ForwardIterator first, ForwardIterator last) {
    /* ... */
}

您可以将此函数称为:
std::vector<boost::shared_ptr<Child> > listOfChilds = getList();
computeStuff(listOfChilds.begin(), listOfChilds.end());

采取一对迭代器而不是容器有很多优点,但是这里的两个主要优点是
  • computeStuff函数可以接受任何类型的容器范围,而不仅仅是std::vector
  • 该范围仅包含可转换为您要使用的类型的对象(例如boost::shared_ptr<Parent>),实际上它不必包含该特定类型的对象。
  • 07-28 02:45
    查看更多