回调函数是一个很有用,也很重要的概念。当发生某种事件时,系统或其他函数将会自动调用你定义的一段函数。回调函数在windows编程使用的场合很多,比如Hook回调函数:MouseProc,GetMsgProc以及EnumWindows,DrawState的回调函数等等,还有很多系统级的回调过程。 一般情况下, 我们使用的回调函数基本都是采用C语言风格. 这里介绍一种C++风格的回调对象方法. 采用template实现.
template < class Class, typename ReturnType, typename Parameter >
class SingularCallBack
{
public:
typedef ReturnType (Class::*Method)(Parameter);
SingularCallBack(Class* _class_instance, Method _method)
{
//取得对象实例地址,及调用方法地址
class_instance = _class_instance;
method = _method;
};
ReturnType operator()(Parameter parameter)
{
// 调用对象方法
return (class_instance->*method)(parameter);
};
ReturnType execute(Parameter parameter)
{
// 调用对象方法
return operator()(parameter);
};
private:
Class* class_instance;
Method method;
};