Title / Description
Code #include <iostream> #include <list> class ScopeCaller { template <class C, void (C::*method)()> static void method_thunk(void* obj) { (static_cast<C*>(obj)->*method)(); } template <void (*cb)()> static void function_thunk(void*) { (*cb)(); } struct handle { handle(void* d, void (*cb)(void*)) : data(d), callback(cb) { } void operator()(){ callback(data); } void* data; void (*callback)(void*); }; public: ~ScopeCaller() { while(!_cbs.empty()) { (*_cbs.back())(); delete _cbs.back(); _cbs.pop_back(); } } template <class C, void (C::*method)()> void Register(C& obj) { _cbs.push_back(new handle((void*)&obj, &method_thunk<C, method>)); } template <void (*cb)()> void Register() { _cbs.push_back(new handle(NULL, &function_thunk<cb>)); } private: std::list<handle*> _cbs; }; //--------------------------------------------------------------------------- void StaticCallback() { std::cout << "Static Callback!" << std::endl; } class ClassBack { public: void Call() { std::cout << "ClassBack::Call!" << std::endl; } }; int main(int, char**) { ScopeCaller exit; exit.Register<&StaticCallback>(); ClassBack cb; exit.Register<ClassBack, &ClassBack::Call>(cb); return 0; }
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code