重构,其中唯一函数具有不同的参数
Refactoring where unique functions have different arguments
我有一个类(充当库的包装器),其成员函数都遵循以下模式:
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
.
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类