我目前正在使用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
强制转换,它会起作用,但是安全吗?
顺便说一句,这些是时间敏感的回调,重型虚拟化方案被认为是不切实际的 :/