用c++11封装win32界面库 (四)

2014-11-24 03:23:30 · 作者: · 浏览: 3
) { // call的时候遍历vector,每个call一遍
for(auto& h : handlers)
h(args...);
}
};

template
struct event_handler {
typedef function fn_t;
vector handlers; //每次 += 就放到这个vector中

void operator+=(fn_t f) {
handlers.push_back(f);
}
void operator()(_t... args) { // call的时候遍历vector,每个call一遍
for(auto& h : handlers)
h(args...);
}
};然后是各种 event_handler


[cpp]
namespace event {

struct base {
event_handler move;
event_handler size;
event_handler paint;
event_handler enable;
// ...

virtual void process_msg(wnd_msg& msg) {
switch(msg.type) {
case WM_MOVE: move(pos(msg.lp.loword(), msg.lp.hiword())); break;
case WM_SIZE: size(size(msg.lp.loword(), msg.lp.hiword())); break;
case WM_PAINT: paint(msg); break;
case WM_ENABLE: enable(!(msg.wp == 0)); break;
// ...
}
}
};
}

namespace event {

struct base {
event_handler move;
event_handler size;
event_handler paint;
event_handler enable;
// ...

virtual void process_msg(wnd_msg& msg) {
switch(msg.type) {
case WM_MOVE: move(pos(msg.lp.loword(), msg.lp.hiword())); break;
case WM_SIZE: size(size(msg.lp.loword(), msg.lp.hiword())); break;
case WM_PAINT: paint(msg); break;
case WM_ENABLE: enable(!(msg.wp == 0)); break;
// ...
}
}
};
}
每个类都有一个 event 成员


[cpp]
template
struct wnd_base : wnd32 {

event_t event;

virtual void process_msg(wnd_msg& msg) {
event.process_msg(msg); // thunk 把消息发送给 wnd_base::process_msg,这里再调用event.process_msg
}
};

template
struct wnd_base : wnd32 {

event_t event;

virtual void process_msg(wnd_msg& msg) {
event.process_msg(msg); // thunk 把消息发送给 wnd_base::process_msg,这里再调用event.process_msg
}
};

5 initor
常见的类设计是提供多个构造函数以支持不同的参数[cpp] view plaincopyprint class window {
window() {}
window(string text) { ... }
window(string text, int w, int h) { ... }
window(string text, int w, int h, int x, int y) { ... }
...
};

window w("title", 100, 200, 300, 400);// 很容易记错,到底 100,200是长宽,还是xy坐标

class window {
window() {}
window(string text) { ... }
window(string text, int w, int h) { ... }
window(string text, int w, int h, int x, int y) { ... }
...
};

window w("title", 100, 200, 300, 400);// 很容易记错,到底 100,200是长宽,还是xy坐标
所以有了 initor,或者叫 create_info, wnd_init, 用来存放创建信息,每个实例都保存一份initor, create() 的时候会去拿 initor 里的各种信息(text, size...)


[cpp]
wnd w = new_