繁体   English   中英

在对象中存储包含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;
}

从这里我得到错误

stackoverflow_datetimehandler.cpp:在构造函数'DateTimeParse :: DateTimeParse()'中:stackoverflow_datetimehandler.cpp:16:95:错误:没有匹配函数来调用'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

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM