Maximilian
Maximilian

Reputation: 774

C++ using passed function

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()
 }

Upvotes: 7

Views: 437

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

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();

Upvotes: 12

Related Questions