Re: Callback Trouble
On Fri, 16 Nov 2007 19:26:59 -0800 (PST), Nashirak wrote:
I am trying to implement callbacks in C++. I am modeling my callbacks
after some of the stuff that was done in wxWidgets (if anyone is
familiar with that). The syntax is as follows:
[...]
Now the error I am getting is as follows (in Visual Studio 2003):
error C2664: 'NGMX::KM_Keymap::AddKeymapEntryMethod' : cannot convert
parameter 5 from 'void (__thiscall My_Plugin::* )(void)' to
'NGMX::KMKeyboardMethod'
Types pointed to are unrelated; conversion requires reinterpret_cast,
C-style cast or function-style cast
AFAICS, the problem is that member function pointers are not
polymorphic in C++. The following is a Reader's Digest version of your
code with some additions:
class KeyboardEvent;
class PI_PluginAPI {
};
typedef
void (PI_PluginAPI::*KMKeyboardMethod)(const KeyboardEvent *event);
class KM_Keymap : public PI_PluginAPI {
public:
bool AddKeymapEntryMethod(PI_PluginAPI *obj, KMKeyboardMethod func);
};
class My_Plugin : virtual public PI_PluginAPI
{
public:
void ShowStuffCB(const KeyboardEvent *event);
void foo() {
// works: calling member function via member function pointer
((*this).*(&My_Plugin::ShowStuffCB))(0);
// doesn't work: what you try to do would be similar to
// the following
PI_PluginAPI* pApi = this;
((*pApi).*(&My_Plugin::ShowStuffCB))(0);
// see error message: a pointer to a (non-static) derived class
// member function is not an pointer to a base memebr class
// function
m_keymap.AddKeymapEntryMethod(this, &My_Plugin::ShowStuffCB);
}
private:
KM_Keymap m_keymap;
};
BTW, a good callback library can be found here:
http://www.codeproject.com/cpp/FastDelegate.asp
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch