Instead of static methods and walking around a pointer to an instance of a class, you can use the functionality in the new C ++ 11 standard: std::function and std::bind :
Now the addHandler method accepts the argument std::function , and this "function object" has no return value and takes an integer as an argument.
To bind it to a specific function, you use std::bind :
class MyClass { public: MyClass(); // Note: No longer marked `static`, and only takes the actual argument void Callback(int x); private: int private_x; }; MyClass::MyClass() { using namespace std::placeholders; // for `_1` private_x = 5; handler->addHandler(std::bind(&MyClass::Callback, this, _1)); } void MyClass::Callback(int x) { // No longer needs an explicit `instance` argument, // as `this` is set up properly cout << x + private_x << endl; }
You need to use std::bind when adding a handler, since you explicitly need to specify the implicit this pointer as an argument. If you have a standalone function, you do not need to use std::bind :
void freeStandingCallback(int x) {
Having an event handler uses std::function objects, and also allows you to use the new C ++ 11 lambda script functions :
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
Some programmer dude Jan 07 '13 at 3:41
source share