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!

0

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Also, consider using event_handler = std::function<void(std::string)> - it will accept a larger number of callable objects, not just functions but also lambda expressions etc.
...and add a huge overhead
@cubuspl42 True. But not always. stackoverflow.com/questions/12452022/…
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];

Comments

3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.