C ++ using the passed function

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

class XY { public: void first(void f()); void second(); }; void XY::first(void f()){ } void XY::second(){ f(); //passed function from first() } 
+7
c ++ c ++ 11
source share
1 answer

You can use std :: function to save the called and subsequent call.

 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 an instance of X and install the called:

 X x; x.set(f); 

Call the saved caller later:

 x.call(); 
+12
source share

All Articles