Skip to content

Instantly share code, notes, and snippets.

@solkar
Created April 18, 2014 07:20
Show Gist options
  • Save solkar/11029099 to your computer and use it in GitHub Desktop.
Save solkar/11029099 to your computer and use it in GitHub Desktop.
C++ callbacks
#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
fCallback = callback
}
void performCallback()
{
fCallback(1);
}
private:
std::function<void(int)> fCallback;
};
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