Ok, although I don't use std::function too often, I noticed some things to improve:
- you are leaking memory
- why don't you just let users register a std::function object directly?
Where? You mean in the test code? If so, I know, I was just testing so I didn't care . If the dispatcher is leaking memory, however, that is another story.
In addition, you could hide some boilerplate (event id , event base ) with this technique:
unsigned int next_id()
{
unsigned int previous_id = 0;
return ++previous_id; //or return previous_id++ , depending on wheter you need a NULL value
}
template< class Type >
class type_id
{
public:
static unsigned int value;
};
template< class Type >
unsigned int type_id< Type >::value = next_id(); //unique value for each type
Indeed! Very nice, that is a much better way of doing it. I salute you sir.
To save the map lookup, you could use a vector whose size is as big as the number of EventType s you have instead of a map.
(to do is, check in register and dispatch whether your vector is large enough and resize it if needed).
Then you can just access the listener_vector for any type T with
listener_vectors[ type_id< T >::value ];
which has O(1), but probably consumes more memory if you have multiple dispatchers.
I thought of this, but was unsure if I should do it this way or not. It would surely consume more memory, but hopefully to a lesser extent if I use a vector of vector pointers and set the thus far unused ones to NULL until they are needed for the first time.