I m trying to code the following situation: I have a base class providing a framework for handling events. I m trying to use an array of pointer-to-member-functions for that. It goes as following:
class EH { // EventHandler
virtual void something(); // just to make sure we get RTTI
public:
typedef void (EH::*func_t)();
protected:
func_t funcs_d[10];
protected:
void register_handler(int event_num, func_t f) {
funcs_d[event_num] = f;
}
public:
void handle_event(int event_num) {
(this->*(funcs_d[event_num]))();
}
};
然后,用户应当从这个班子中学习其他班级,并提供操作员:
class DEH : public EH {
public:
typedef void (DEH::*func_t)();
void handle_event_5();
DEH() {
func_t f5 = &DEH::handle_event_5;
register_handler(5, f5); // doesn t compile
........
}
};
这部法律汇编了,因为DEH:func_t 不能转换成EH:func_t。 这对我来说是完美的。 在我的情况下,转换是安全的,因为按照<代码>的条目<>/代码>的物体实际上是DEH。 因此,我要谈谈:
void EH::DEH_handle_event_5_wrapper() {
DEH *p = dynamic_cast<DEH *>(this);
assert(p != NULL);
p->handle_event_5();
}
而是
func_t f5 = &DEH::handle_event_5;
register_handler(5, f5); // doesn t compile
in DEH::DEH() put
register_handler(5, &EH::DEH_handle_event_5_wrapper);
So, finally the question (took me long enough...):
Is there a way to create those wrappers (like EH::DEH_handle_event_5_wrapper
) automatically?
Or to do something similar?
What other solutions to this situation are out there?
感谢。