vendredi 4 décembre 2015

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

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?

Aucun commentaire:

Enregistrer un commentaire