重构,其中唯一函数具有不同的参数

Refactoring where unique functions have different arguments

本文关键字:参数 函数 唯一 重构      更新时间:2023-10-16

我有一个类(充当库的包装器),其成员函数都遵循以下模式:

MyObject& MyObject::ObjectFunction(int arg1, std::string arg2)
{
    LibraryObject destination_object;
    libraryFunction(destination_object, arg1, arg2);
    setProp(destination_object);
    ~destination_object;
    return *this;
}

我想重构它,以便可以将重复的步骤(创建目标对象、设置属性、销毁目标对象、返回地址)移动到它们自己的函数中,理想情况下是这样的:

MyObject& MyObject::genericFunction (uniqueLibraryFunction(Args)) 
{
    LibraryObject destination_object;
    uniqueLibraryFunction(Args);
    setProp(destination_object);
    ~destination_object;
    return *this;        
}
void libraryFunction1(int arg1, std::string arg2) 
{
    genericFunction(libraryFunction1(arg1, arg2));
}
void libraryFunction2(double arg1, int arg2) 
{
    genericFunction(libraryFunction2(arg1, arg2));
}

但是,我正在使用一个库,该库具有需要目标对象返回值的方法。我尝试使用可变参数,但我似乎无法让它工作,因为库函数采用不同的参数长度和类型。我也尝试使用指向函数成员的指针,但由于同样的原因无法让它工作(函数之间的参数长度和类型不同)。

我的类代码如下:

class MyObject 
{
    private:
        LibraryObject prop;
    public:
        getProp();
        setProp(int prop);
}

如果我正确理解了这个问题,那么它应该可以用lambda来实现:

template <class F>
MyObject& MyObject::genericFunction(F f) 
{
    LibraryObject destination_object;
    f(destination_object);
    setProp(destination_object);
    return *this;        
}
void MyObject::libraryFunction1(int arg1, std::string arg2) 
{
    genericFunction([=](LibraryObject &o) { libraryFunction1(o, arg1, arg2); });
}
void libraryFunction2(double arg1, int arg2) 
{
    genericFunction([=](LibraryObject &o) { libraryFunction2(o, arg1, arg2); });
}

或者,std::bind将执行相同的工作:

void MyObject::libraryFunction1(int arg1, std::string arg2) 
{
  genericFunction(std::bind(libraryFunction1, std::placeholders::_1, arg1, arg2));
}

模板应该不是问题,因为如果它是私有的,它可以很容易地在源文件中实现,所有对它的调用都驻留在那里。但是,如果出于某种原因不适合您,您可以使用 std::function<void(LibraryObject&)> 而不是 F .