c++ - 重构唯一函数具有不同参数的地方
问题描述
我有一个类(充当库的包装器),其成员函数都遵循这种模式:
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
.
推荐阅读
- python - 我应该创建一百万个队列(Python)
- python - 计算二叉树中的路径
- c++ - 什么是查看函数是否公开的快速方法?
- google-cloud-datastore - 如何定期更新 Google Datastore 中的适量数据(约 250 万条条目)?
- python - 如何在位于 tk.Canvas 内的 tk.Frame 中添加两个小部件?
- php - 使用 REST API 发起对 Twilio 注册 SIP 的调用
- tensorflow - 无法使用 tensorflow-gpu 1.8.0 conda 包访问 GPU
- java - 在 Java Spring 中以 REST 方法返回后执行清理操作
- wordpress - 生成电子邮件优惠券 Wordpress
- c# - 如何在 SAP Crystal 报表中格式化阿拉伯日期名称 ar-AR 或 en-EN