Simple Callback question,(then y am I asking it? :) )
I have a simple callback in one of my classes that works great.
class CGameMenu
{
typedef void (_stdcall* MENUBUTTONCLICKED)(int);
.....
void SetMenuButtonClicked(MENUBUTTONCLICKED pCallback){pMenuButtonClicked = pCallback;}
......
MENUBUTTONCLICKED pMenuButtonClicked;
};
works great from the main cpp file, which is not a class. I define it like this
in the OnCreateDevice
pGameMenu->SetMenuButtonClicked(NavClicked);
void _stdcall NavClicked(int ID); //in the header file
void _stdcall NavClicked(int ID) // in the cpp file
{
}
now I'm trying to set it from another class though and I receive a error.
pGameMenu->SetMenuButtonClicked(NavClicked);
....\My Documents\Visual Studio Projects\GamePrj\Parts\PuzzleViewer\Puzzle.h(84): error C2664: 'CGameMenu::SetMenuButtonClicked' : cannot convert parameter 1 from 'void (int)' to 'CGameMenu::MENUBUTTONCLICKED'
I've tried to set it as static and I've tried a few examples from Microsoft. What's really bugging me is I've successfully done this before and had no problems. I can't remember what I did different though.
Any ideas????
Thanks
Bubba Richard
The problem that you have here is that typedef void (_stdcall* MENUBUTTONCLICKED)(int); is just a regular function pointer, if you want a pointer to a member function you need to do typedef int (ClassName::MENUBUTTONCLICKED*)(int);
Here is some more information on member function pointers
This obviously isn't ideal because a) you don't know what the class is going to be and b) because it means you have to seperate your member function from your free functions, when really you just want one nice interface SetMenuButtonClicked which works for all callable entities.
Luckily, boost::function gives you a nice generalised solution that works for both member functions and free functions :
Here is some more information on member function pointers
This obviously isn't ideal because a) you don't know what the class is going to be and b) because it means you have to seperate your member function from your free functions, when really you just want one nice interface SetMenuButtonClicked which works for all callable entities.
Luckily, boost::function gives you a nice generalised solution that works for both member functions and free functions :
class CGameMenu{typedef boost::function<void(int)> MENUBUTTONCLICKED;.....void SetMenuButtonClicked(MENUBUTTONCLICKED pCallback){pMenuButtonClicked = pCallback;}......// calling the callback is just like a normal function pointer callvoid OnButtonClicked(int val) { pMenuButtonClicked(val); }MENUBUTTONCLICKED pMenuButtonClicked;};
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement