将方法传递给方法并替换(几乎完全相同)重复代码

pass method to method and replace (almost exactly same) repeating code

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

我有两种非常相似的方法。他们之间的主要区别在于他们在某个时候调用了另一种不同的方法。例如:

// method 1
method1(){
  // same code for Method1 and Method2 before calling different method
  methodA();
  // same code for Method1 and Method2 after calling different method
}
// method 2
method2(){
  // same code for Method1 and Method2 before calling different method
  methodB();
 // same code for Method1 and Method2 after calling different method
}

我想创建一个方法(method(,该方法将能够调用两个不同的方法(methodAmethodB(。我想这应该通过多态性(如果我错了,请正确正确(,例如:

method(Parent obj){
  // same code for Method1 and Method2 before calling different method
  obj->methodAB();
  // same code for Method1 and Method2 after calling different method
}
class Parent{
public:
  virtual int methodAB();
};
// methodA implementation
Class ChildA: public Parent{
public:
 int methodAB();
}
// methodB implementation
Class ChildB: public Parent{
public:
 int methodAB();
}

实际呼叫将是:

Parent *obj = new ChildA; // or Parent *obj = new ChildB;
method1(obj)
delete obj;

但是有一个严重的问题:在我的情况下,methodA()methodB()作为参数不同的类型,因此我的情况实际上是:

method1(obj_type1){
  // same code for Method1 and Method2 before calling different method
  methodA(obj_type1);
  // same code for Method1 and Method2 after calling different method
}

method2(obj_type2){
  // same code for Method1 and Method2 before calling different method
  methodB(obj_type2);
 // same code for Method1 and Method2 after calling different method
}

是否可以在带有不同类型的参数的派生类中实现虚拟函数,还是有其他优雅的解决方案来解决此问题?

因此,将常见代码重构到其他功能中,并调用两个方法(成员函数(:

method1(){
  common_code_1();
  auto result = methodA(obj_type1);
  common_code_2(result);
}

method2(){
  common_code_1();
  auto result = methodB(obj_type2);
  common_code_2(result);
}

您可以使用模板去做您想做的事,这些行:

void foo1(int i)
{
}
void foo2(double d)
{
}
template<typename ArgType, void (*Func)(ArgType arg)>
void DoIt(ArgType a)
{
  // Common 1
  Func(a);   
  // Common 2
}
int main()
{
    DoIt<int, foo1>(1);
    DoIt<double, foo2>(1.0);
   return 0;
}

Func不需要是 void,它可以返回 bool,或者如果您需要进行处理。