我目前正在使用 Don Clugston 的 fastdelegates 实现计时器/回调系统。(见http://www.codeproject.com/KB/cpp/FastDelegate.aspx)
这是起始代码:
struct TimerContext
{
};
void free_func( TimerContext* )
{
}
struct Foo
{
void member_func( TimerContext* )
{
}
};
Foo f;
MulticastDelegate< void (TimerContext*) > delegate;
delegate += free_func;
delegate += bind( &Foo::member_func, &f );
好的,但是现在,我希望用户能够子类TimerContext
化以存储并将他自己的结构发送到回调。这里的目的是防止用户不得不低调TimerContext
自己
struct TimerContext
{
};
struct MyTimerContext : TimerContext
{
int user_value;
};
void free_func( TimerContext* )
{
}
void free_func2( MyTimerContext* )
{
}
struct Foo
{
void member_func( TimerContext* )
{
}
void member_func2( MyTimerContext* )
{
}
};
Foo f;
MulticastDelegate< void (TimerContext*) > delegate;
delegate += free_func;
delegate += free_func2;
delegate += bind( &Foo::member_func, &f );
delegate += bind( &Foo::member_func2, &f );
如您所料,GCC 不会让我这样做 :)
error: invalid conversion from `void (*)(MyTimerContext*)' to `void (*)(TimerContext*)'
error: initializing argument 1 of `delegate::Delegate<R ()(Param1)>::Delegate(R (*)(Param1)) [with R = void, Param1 = TimerContext*]'
所以现在我的问题是:如果我强制演员使用reinterpret_cast
,它会起作用,但它会安全吗?
PS:这些是时间关键的回调,重的面向虚拟的解决方案被认为是不切实际的:/