Map of function pointers

Hi Experts,

I need to store some callback functions and associated int values in a map.  Basically, I want to notify the registered listeners of events.

The callback functions will be in the format ( C style function )
void callback(Event *evt) { }

Could you please let me know how to do this in C++?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Well, that could basically be like
#include <map>
using namespace std;

typedef void (*event_callback)(Event *evt);
typdef unsigned ine event_type;

map<event_type,event_callback> mapEvents;

// ...

#define SOME_EVENT 1
void do_some_event(Event *evt) { }

// ...

int main () {

  pair<map<event_type,event_callback>::iterator,bool> p = mapEventss.insert(map<event_type,event_callback>::value_type(SEOME_EVENT,do_some_event));

  // ...

  event_callback cb;

  map<event_type,event_callback>::iterator i = mapEvents.find(SOME_EVENT);

  if (i != mapEvents.end()) cb = *i;

  Event e;

  (*cb)(&e); // do the call
  return 0;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ambuliAuthor Commented:
Thank you JKR.
You're most welcome - just saw one typo and some need for more explanation in the same line:
pair<map<event_type,event_callback>::iterator,bool> p = mapEvents.insert(map<event_type,event_callback>::value_type(SEOME_EVENT,do_some_event));

  // 'p' can be used to check if a handler already existd:

  if (!p.second) throw("An event handler for this type already exists in the map!");

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.