Sign in to follow this  
bubba_richard

Simple Callback question,(then y am I asking it? :) )

Recommended Posts

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

Share this post


Link to post
Share on other sites
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 :


class CGameMenu
{
typedef boost::function<void(int)> MENUBUTTONCLICKED;
.....

void SetMenuButtonClicked(MENUBUTTONCLICKED pCallback){pMenuButtonClicked = pCallback;}

......

// calling the callback is just like a normal function pointer call
void OnButtonClicked(int val) { pMenuButtonClicked(val); }

MENUBUTTONCLICKED pMenuButtonClicked;
};

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this