Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using passed function

Tags:

c++

c++11

I have two functions one of them takes a function as an argument this works just fine, but I want to call this passed function in my second one.

class XY {   
 public:

   void first(void f());
   void second();        
 };

 void XY::first(void f()){

 }

 void XY::second(){
 f(); //passed function from first()
 }
like image 326
Maximilian Avatar asked Feb 25 '17 11:02

Maximilian


1 Answers

You might use std::function to store the callable and call it later.

class X {
    public:
        void set(std::function<void()> f) {
            callable = f;
        }

        void call() const {
            callable();
        }

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

void f() {
    std::cout << "Meow" << std::endl;
}

Then create X instance and set the callable:

X x;
x.set(f);

Later call the stored callable:

x.call();
like image 90
Edgar Rokjān Avatar answered Oct 13 '22 01:10

Edgar Rokjān