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 {
    DateTimeFormat(std::function<void(int)> fFunc) : m_func(fFunc) {};
    std::function<void(int)> m_func;

class DateTimeParse {
    DateTimeParse() {
      DateTimeFormat(std::bind(&DateTimeParse::setYear, std::placeholders::_1));
    void setYear(int year) {m_year = year;};
    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?


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

Need Your Help

Dynamically determine audio container in Exoplayer

java android media audio-streaming exoplayer

I'm trying to use the ExtractorSampleSource to extract different audio files, some are .AAC some .M4A and some .MP3. Is there a way to dynamically determine which extractor (AdtsExtractor, Mp4Extr...

thread_local vector segmentation fault at end of program in C++

c++ multithreading vector

I'm trying to make a multi-threaded program but am having a weird problem with thread local vectors. Here's the (stripped-down to only have the error) code: