I found this code for event handler with registration style in c++. Can anyone explain me, what the below code does?
#include <algorithm>
#include <functional>
#include <list>
class Button {
public:
typedef void (*OnPress)(Button *, void *closure);
private:
typedef std::pair<OnPress, void*> PressCallBack;
std::list<PressCallBack> onPress;
struct Notify:
public std::binary_function<PressCallBack, Button*, void> {
void operator()( PressCallBack& c, Button* b) const {
(*c.first)(b, c.second);
}
};
void NotifyAll(void){
std::for_each(
onPress.begin(), onPress.end(),
std::bind2nd(Notify(), this)
);
}
public:
void AddOnButtonPress(OnPress f, void *c){
onPress.push_back(PressCallBack(f,c));
}
void RemoveOnButtonPress(OnPress f, void *c){
onPress.remove(PressCallBack(f,c));
}
};
Any comment will be helpful!!! Thanks in advance!
Somewhere there are functions with the signature:
void function_name(Button* btn, void* ptrToSomeData);
The functions with the second parameter (ptrToSomeData) can be added into the list of event handlers with the function Button::AddOnButtonPress:
Button::AddOnButtonPress(function_name, &SomeData);
when the function Button::NotifyAll() is called for some object SomeButton, then all added functions will be called in the order in which they were added. The first argument will be passed a pointer to the button (SomeButton), and the second argument will be the one specified when adding.
typedef void (*OnPress)(Button *, void *closure);
//< declare OnPress as pointer to function (pointer to Button, pointer to void) returning void
typedef std::pair<OnPress, void*> PressCallBack;
//< declare pair of
//< - pointer to function (pointer to Button, pointer to void) returning void
// and
//< - pointer to void
//This type is used to store the pointer to callback function with the second argument of the function
std::list<PressCallBack> onPress; //< list of saved callbacks
struct Notify:
public std::binary_function<PressCallBack, Button*, void> {
void operator()( PressCallBack& c, Button* b) const {
(*c.first)(b, c.second);
}
};
//< the type Notify - it is functor. It is used this way:
// Notify()(callback, this);
// so
// it calls callback_function(this, store_pointer_to_some_data)
void NotifyAll(void){
std::for_each(
onPress.begin(), onPress.end(),
std::bind2nd(Notify(), this)
);
}
//< for every stored callback:
// 1) create object Notify
// 2) call Notify::operator()(PressCallBack, this)
void AddOnButtonPress(OnPress f, void *c){
onPress.push_back(PressCallBack(f,c));
}
//< store callback function 'f' and second argument 'c' for the callback function 'f' into onPress list
void RemoveOnButtonPress(OnPress f, void *c){
onPress.remove(PressCallBack(f,c));
}
//< store callback function 'f' with the second argument 'c' from onPress list