在对象中存储一个std::函数,该函数包括std::占位符



我正在尝试编写一些代码,将函数(带参数)存储为对象成员,以便以后可以以通用方式调用它。目前,我的示例使用std::function和std::bind。

#include <functional>
class DateTimeFormat {
  public:
    DateTimeFormat(std::function<void(int)> fFunc) : m_func(fFunc) {};
  private:
    std::function<void(int)> m_func;
};
class DateTimeParse {
  public:
    DateTimeParse() {
      DateTimeFormat(std::bind(&DateTimeParse::setYear, std::placeholders::_1));
    };
    void setYear(int year) {m_year = year;};
  private:
    int m_year;
};
int main() {
  DateTimeParse dtp;
}

从这里我得到错误

stackoverflow_datetimehandler.cpp:在构造函数"DateTimeParse::DateTimeParse()"中:stackoverflow_datetimehandler.cpp:16:95:错误:没有用于调用"DateTimeFormat::DateTimeFormat(char,int,int,std::_Bind_helper&>::type)"的匹配函数DateTimeFormat('Y',419003000,std::bind(&DateTimeParse::setYear,std:;占位符::_1));

我不认为这是因为我的构造函数没有声明正确的参数类型。但我不确定我是否朝着正确的方向前进。有没有更好的方法来完成这项任务?如果这是处理这个问题的好方法,那么我该如何解决这个问题并保留占位符?

非静态成员函数必须绑定到对象,因此必须更改为:

  DateTimeFormat(std::bind(&DateTimeParse::setYear, this, std::placeholders::_1));

也就是说,您还必须绑定this

实时演示

相关内容

最新更新