在对象中存储包含 std::placeholders 的 std::function

Storing a std::function that includes std::placeholders in an object

我正在尝试编写一些代码,将函数(带有参数)存储为对象成员,以便稍后以通用方式调用它。目前我的示例使用 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;
}

由此我得到错误

Whosebug_datetimehandler.cpp: In constructor ‘DateTimeParse::DateTimeParse()’: Whosebug_datetimehandler.cpp:16:95: error: no matching function for call to ‘DateTimeFormat::DateTimeFormat(char, int, int, int, std::_Bind_helper&>::type)’ DateTimeFormat('Y',4,1900,3000,std::bind(&DateTimeParse::setYear, std::placeholders::_1));

我不是,因为我的构造函数没有声明正确的参数类型。但我不确定我是否朝着正确的方向前进,以实现我想要实现的目标。是否有更好的方法来执行此任务?如果这是处理此问题的好方法,那么我该如何继续解决此问题并保留占位符?

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

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

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

Live Demo