Replace the callback function with a functor - they can save state. Example functor:
#include <iostream> #include <memory> class Functor { private: std::shared_ptr<int> m_count; public: Functor() : m_count(new int(0)) {} void operator()() { ++(*m_count); // do other stuff... } int count() const { return *m_count; } }; template <typename F> void f(F callback) { // do stuff callback(); // do other stuff } int main() { Functor callback; f(callback); f(callback); std::cout << callback.count(); // prints 2 return 0; }
Pay attention to the use of shared_ptr inside the functor - this is because f has a local copy of the functor (pay attention to the pass-by-value), and you want this copy to share its int with the functor that you have access to. Also note that f must take its argument by value, since you want to support all the called objects, not just functors.
Stuart golodetz
source share