#include #include #include "Header.h" // the implementation is here /* * https://stackoverflow.com/questions/2298242/callback-functions-in-c */ using namespace std; // a dummy enum for this example enum EventEnum { EVENT1, EVENT2, EVENT3 }; /************************************************************************************************************** * */ class MyClassWithMethod { public: unsigned int age = 12; enum { MALE, FEMALE } sex; void registerCB(Dispatcher& dispatcher) { using namespace std::placeholders; dispatcher.addCB(std::bind(&MyClassWithMethod::listener, this, _1, _2, _3)); } #if 1 void registerCB(Dispatcher& dispatcher) { using namespace std::placeholders; dispatcher.addCB(std::bind(&MyClassWithMethod::listener2, this, _1, _2)); } #endif #if 0 void registerCB(Dispatcher& dispatcher) { using namespace std::placeholders; dispatcher.addCB(std::bind(&MyClassWithMethod::listener, this, _1, _2, _3)); } #endif private: // any method with the right signature can be used: void listener(int i, long l, double d) { cout << "listener() for " << this << ", got: " << i << ", " << l << ", " << d << endl; } void listener2(string str, EventEnum evt) { cout << "listener() for " << this << ", got: " << str << ", " << evt << endl; } }; /************************************************************************************************************** * */ // template void myCb(string str, EventEnum evt) { cout << "myCb: " << str << " got event " << evt << endl; } int main(int argc, char* argv[]) { // 2 example dispatchers, any number of arguments and types can be used: Dispatcher d1;// here any cb(string, EventEnum) can register Dispatcher d2;// here any cb(int, long, double) can register uint8_t mainAge = 12; // // From the "most simple" lambda usage example ... // auto cbid1 = d1.addCB([&](string str, EventEnum evt) { cout << "CB1:" << str << " got event " << evt << endl; }); auto cbid2 = d1.addCB([=](string str, EventEnum evt) { cout << "CB2:" << str << " got event " << evt << endl; }); auto cbid3 = d1.addCB(&myCb); // d1.broadcast("** Dispatching to 2 is **", EVENT1); // d1.broadcast("** E a s y **", EVENT2); // d1.delCB(cbid1); // remove the first callback // d1.broadcast("** Dispatching to 1 is **", EVENT1); // d1.broadcast("** E a s y **", EVENT2); // d1.delCB(cbid2); // remove the second callback // d1.broadcast("** No one will see this **", EVENT3); // ... to the "most complex" **live** instance (not copy) usage example: MyClassWithMethod instance1; MyClassWithMethod instance2; instance1.registerCB(d1); instance2.registerCB(d2); // instance1.registerCB(myCb); d1.broadcast("myEvent", EVENT3); d2.broadcast(65000, 12345678910, 3.14159265); d2.broadcast(56000, 1987654321, 14159265.3); return 0; }