如何在本例中避免代码重复

How to avoid code duplication in this example?

本文关键字:代码      更新时间:2023-10-16

我有两个类,BaseDerived。我提供了一个函数,将一个函数应用于Base的所有元素,以及另一个函数,将一个函数应用于Derived的所有元素:

#include <iostream>
#include <vector>
class Base {
  typedef std::vector<int> Vec;
  typedef Vec::const_iterator CIter;
  CIter begin() const;
  CIter end() const;
};
class Derived : public Base {
  void add(int);
};

template<class F>
void processBase(const Base& b, F& f) {
  for (Base::CIter it = b.begin(); it != b.end(); ++it) {
    f(b, *it);
  }
}
template<class F>
void processDerived(Derived* d, F& f) {
  for (Base::CIter it = d->begin(); it != d->end(); ++it) {
    f(d, *it);
  }
}

我怎样才能使一个函数调用另一个函数,这样我就不会有代码重复?(我只举了一个最小的例子;在我的实际代码中,for循环有点复杂,并且该代码在两个函数中完全重复。

我必须模板processBase函数吗?或者是否有一种使用casting的方法?

假设const Base&Derived*的差异是一个错误,是的,您需要一个函数模板来调用具有正确实参类型的函子:

template <typename Collection, typename F>
void processCollection (Collection& col, F& f) {
    for (typename Collection::CIter i=col.begin(); i!=col.end(); ++i) {
        f (col, *i);
    }
}

processCollection适用于const或非const, BaseDerived对象