我正在使用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:這些是時間關鍵的回調,重面向虛擬的解決方案被認爲是不可行的:/
Howw,好嗎:(感謝您參考! – NewbiZ
即使提振::函數將不會在他的情況下工作,因爲TimerContext *不能隱式轉換到MyTimerContext *。我提到這個類型安全問題,我答案但由於某種原因,我得到了downvoted – sellibitze