[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 323
  • Last Modified:

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++?

  • 2
1 Solution
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

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


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now