如果您想要更精确的控制,可以使用函数对象(functors),这比通用方法更为有效。以下是使用我的win32 api将api消息从一个类转发到另一个类的示例。
IListener.h
#include <windows.h>
class IListener {
public:
virtual ~IListener() {}
virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};
Listener.h
#include "IListener.h"
template <typename D> class Listener : public IListener {
public:
typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
private:
D* _instance;
WMFuncPtr _wmFuncPtr;
public:
virtual ~Listener() {}
virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override {
return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam);
}
Listener(D* instance, WMFuncPtr wmFuncPtr) {
_instance = instance;
_wmFuncPtr = wmFuncPtr;
}
};
Dispatcher.h
#include <map>
#include "Listener.h"
class Dispatcher {
private:
std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners;
public:
virtual ~Dispatcher() {
IListener* get(UINT uMsg) {
typename std::map<UINT, IListener*>::iterator itEvt;
if((itEvt = _listeners.find(uMsg)) == _listeners.end()) {
return NULL;
}
return itEvt->second;
}
template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) {
_listeners[uMsg] = new Listener<D>(instance, wmFuncPtr);
}
};
使用原则
class Button {
public:
Dispatcher _dispatcher;
LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
return _dispatcher[uMsg](hWnd, uMsg, w, l);
}
};
class Myclass {
Button _button;
LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
return 0;
}
void initialize() {
_button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener);
}
};
祝好运,感谢所有分享知识的人。
std::function
,需要额外将this
指针作为其第一个参数传入,例如std::function<void(Foo*, int, int)> = &Foo::doSomethingArgs
。请注意不要改变原意。 - landerlyoung#include<functional>
。 - Minwoo Yu