This is a class which provides a simple event system mechanism:
template <typename T>
class EventChannel
{
private:
using idType = unsigned int;
static idType& getId()
{
static idType id = 0;
return id;
}
static std::unordered_map<idType, std::function<bool(T)>>& getHandlers()
{
static std::unordered_map<idType, std::function<bool(T)>> handlers;
return handlers;
}
public:
static idType regiterListener(std::function<bool(T)> listener)
{
auto& id = getId();
id++;
getHandlers()[id] = listener;
return id;
}
static void tringgerEvent(T e)
{
for (const auto& h : getHandlers())
{
h.second(e);
}
}
static void removeListener(idType listener_id)
{
getHandlers().erase(listener_id);
}
};
and the usage is like this:
struct TouchEvent
{
int t_id;
float x;
float y;
};
//just for convenience
template <typename T>
void DISPATCH_EVENT(T t)
{
EventChannel<T>::tringgerEvent(t);
}
...
auto lid = EventChannel<TouchEvent>::regiterListener([](TouchEvent ev)->bool
{
cout << "got touch " << ev.t_id << "\n"; return false;
});
DISPATCH_EVENT(TouchEvent{ 10, 2, 4 });
The output would be just as you would expect:
got touch 10
It's also possible to remove the previously set listener:
EventChannel<TouchEvent>::removeListener(lid);
Any insight on what I've done badly wrong would be much appreciated.