I would like to build a generic event-bus in c++, which allows messages of arbitrary type to be passed into it, and which allows registering of handlers based on the type of the message. IE I would like to expose a method like the following:
void registerHandler((OutputType) handler(EventType));
such that after calling this, when future events of type EventType are placed into the bus, it will be able to locate the appropriate handler and run it.
Of course I could handle this by creating some wrapper type ie:
struct EventWrapper {
void* event;
// Denote the type of event this is: we can register and find handlers by the type id.
int event_type;
}
But I am hoping to avoid this, since it necessitates listing and maintaining event_types somewhere. I come from a primarily java background, and c++ templating mystifies me a little bit, so I am struggling to determine whether or not this is possible, and if so how I would go about it.
I'm perfectly willing to have a bunch of messy template magic inside the bus itself, if it allows me to provide the simplified interface I am hoping for externally.
Apologies if this is a duplicate question: it feels like the sort of thing that may be, but I am relatively new to c++ and suspect I do not know the name of the thing I want. I have tried searching for answers without luck. For the same reason I suspect my question title is not ideal :(
Edit: Occurs to me it may be worth mentioning, C++17, and would prefer not to take a dependency to accomplish this but can if it is mandatory / super complicated otherwise.