【问题标题】:Storing a std::function that includes std::placeholders in an object在对象中存储包含 std::placeholders 的 std::function
【发布时间】:2015-12-04 17:41:39
【问题描述】:

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

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

【问题讨论】:

  • 你的意思是std::bind(&amp;DateTimeParse::setYear, this /*&lt;&lt;&lt;*/, std::placeholders::_1) 吗?
  • DateTimeFormat 接受一个参数,一些可调用的可转换为std::function&lt;void(int)&gt;。那么这些到底是什么 - 'Y',4,1900,3000

标签: c++ c++11 std-function stdbind


【解决方案1】:

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

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

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

Live Demo

【讨论】:

  • 但是它保证这个指针保持有效吗?我的意思是,std::function 被初始化为 std::bind()..? 的临时指针
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多