问题描述
我在c ++中找到了具有注册样式的事件处理程序代码。 谁能解释一下下面的代码是什么?
#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));
}
};
任何评论都会有帮助!!! 预先感谢!
解决方法
某些地方带有签名的功能:
void function_name(Button* btn,void* ptrToSomeData);
具有第二个参数(ptrToSomeData)的函数可以通过函数Button :: AddOnButtonPress:添加到事件处理程序列表中。
Button::AddOnButtonPress(function_name,&SomeData);
当某些对象SomeButton调用功能Button :: NotifyAll()时,所有添加的功能将按添加顺序被调用。第一个参数将传递给按钮(SomeButton)的指针,第二个参数将是添加时指定的参数。
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