1

I'm trying to write some code that will store a function (with a parameter) as an object member so that I can call it later in a generic fashion. Currently my example uses std::function and 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;
}

From this I get the error

stackoverflow_datetimehandler.cpp: In constructor ‘DateTimeParse::DateTimeParse()’: stackoverflow_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));

I no that it is because my constructor does not declare the correct parameter type. But I'm not sure if I'm going in the right direction for what I am trying to achieve. Are there better ways for performing this task? If this is a good way to handle this then how do I go forward to solve this and keep the placeholders?

deadpickle
  • 115
  • 2
  • 15

1 Answers1

3

Non static member functions must be bind to an object, thus you would have to change to:

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

That is you would have to bind this as well.

Live Demo

101010
  • 41,839
  • 11
  • 94
  • 168
  • But is it guaranteed that this pointer stays valid? I mean, the std::function is initialised to a pointer from a temporary of std::bind()..? – sebkraemer Jun 01 '17 at 16:34