Created
April 18, 2014 07:20
-
-
Save solkar/11029099 to your computer and use it in GitHub Desktop.
C++ callbacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
class EventHandler | |
{ | |
public: | |
void addHandler(std::function<void(int)> callback) | |
{ | |
fCallback = callback | |
} | |
void performCallback() | |
{ | |
fCallback(1); | |
} | |
private: | |
std::function<void(int)> fCallback; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
{ | |
private_x = 5; | |
handler->addHandler(std::bind(&MyClass::Callback, this, std::placeholders::_1)); | |
} | |
void MyClass::Callback(int x) | |
{ | |
// No longer needs an explicit `instance` argument, | |
// as `this` is set up properly | |
cout << x + private_x << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment