首页 > 解决方案 > 重构唯一函数具有不同参数的地方

问题描述

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

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

标签: c++c++11

解决方案


如果我正确理解了这个问题,那么它应该可以使用 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.


推荐阅读