简体   繁体   中英

Pass function with or without argument as argument in C++

I would like to pass either a void function without an argument or a void function with an argument to a constructor as an argument. Like this:

DailyActivity activity1(&function1)

or

DailyActivity activity2(&function2(uint_t 1))

The function passed should be triggered when DailyActivity::run() is called.

The header of DailyActivity looks like this:

class DailyActivity {
  typedef void (*function_type)();

  public:
    DailyActivity(void (*f)());
    virtual void run();

  private:
    function_type m_function;
};

The constructor and run() function looks like this:

DailyActivity::DailyActivity(void (*f)()) : m_function((*f)) {
}

DailyActivity::run() {
  m_function();
}

But I do not manage to (1) define the typedef in a correct way enabling the two different functions to be accepted and (2) pass the argument o function2 successfully.

You can't do that. Unfortunately C++ can't process partial functions, so you have to overload your constructor to take both function and an argument as two separate arguments and the second one to take care of a parameterless one. Then you're going to have two function pointers and one of them should be null.

Another option is to wrap the functions into a lambda.

You may use std::function with lambda or std::bind :

class DailyActivity {
  public:
    explicit DailyActivity(std::function<void ()> f) : m_function(f) {}
    void run() { m_function(); }

  private:
    std::function<void ()> m_function;
};

And call it

DailyActivity activity1(&function1);
DailyActivity activity2([](){function2(1);});

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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