3

Basically I need to implement an event handler class, but run into an error that I cannot declare an array of voids:

class SomeClass
{
public:
    void registerEventHandler(int event, void (*handler)(std::string));

private:
    // here i get this error: declaration of ‘eventHandlers’ as array of void
    void (*eventHandlers)(std::string)[TOTAL_EVENTS];
}

void SomeClass::registerEventHandler(int event, void (*handler)(std::string))
{
    eventHandlers[event] = handler;
}



void handler1(std::string response)
{
    printf("ON_INIT_EVENT handler\n");
}
void handler2(std::string response)
{
    printf("ON_READY_EVENT handler\n");
}

void main()
{
    someClass.registerEventHandler(ON_INIT_EVENT, handler1);
    someClass.registerEventHandler(ON_READY_EVENT, handler2);
}

Can you help me figure out the exact syntax? Thanks!

LachoTomov
  • 3,312
  • 30
  • 42

3 Answers3

11

This is not array of voids. It's array of function pointers. You should have defined it as follows:

void (*eventHandlers[TOTAL_EVENTS])(std::string);

Or better (C++14):

using event_handler = void(*)(std::string);
event_handler handlers[TOTAL_EVENTS];

Or C++03:

typedef void(*event_handler)(std::string);
event_handler handlers[TOTAL_EVENTS];

But I would rather recommend to do it using vector:

using event_handler = void(*)(std::string);
std::vector<event_handler> handlers;
SGrebenkin
  • 572
  • 4
  • 10
  • 1
    Also, consider `using event_handler = std::function` - it will accept a larger number of callable objects, not just functions but also lambda expressions etc. – MSalters Feb 05 '15 at 11:47
  • ...and add a huge overhead – cubuspl42 Feb 05 '15 at 12:56
  • 3
    @cubuspl42 True. But not always. http://stackoverflow.com/questions/12452022/g-stdfunction-intialized-with-closure-type-always-uses-heap-allocation – SGrebenkin Feb 05 '15 at 13:11
3

You are defining eventHandles as a pointer to a function returning an array of 5 voids, which is not what you intended.

Instead of trying to do this in one line, it will be easier and more readable by using a typedef:

typedef void (*event_handler_t)(std::string);
event_handler_t eventHandlers[TOTAL_EVENTS];
interjay
  • 107,303
  • 21
  • 270
  • 254
3

You mixed the event handler type and the array definition. Separate with typedef:

typedef void(*eventHandler)(std::string);
eventHandler eventHandlers[TOTAL_EVENTS];
harper
  • 13,345
  • 8
  • 56
  • 105