Sign in to follow this  
lpcstr

Creating a EventHandler class

Recommended Posts

lpcstr    127
I need some basic event handling for my library, and I'd rather not include a dependency on boost. Also, the fact that Boost.Signals is the slowest implementation of signals/slots doesn't particularly make me enthusiastic about using it, especially if I don't need all of it's additional functionality.

I'm mainly looking to use this class for handling various UI events like OnKey, OnMouse, etc. Here is what I have so far.

[code]
struct EventArgs
{};

template <typename EventArgType>
class EventHandler
{
public:
typedef std::function<void(EventArgType)> CallbackType;
EventHandler() {}
void Register(CallbackType func)
{
Callbacks.push_back(func);
}
template <typename Object, typename MemPtr>
void Register(Object obj, FuncType ptr)
{
Callbacks.push_back(std::bind(ptr, obj, std::placeholders::_1));
}
void operator()(EventArgType args)
{
FOREACH(Callback, Callbacks)
{
(*Callback)(args);
}
}
private:
std::vector<CallbackType> Callbacks;
};
[/code]

Example usage:

[code]
struct MouseEventArgs : public EventArgs
{
int x, y;
};


EventHandler<MouseEventArgs> OnMouseMoveEvent;

OnMouseMoveEvent.Register(this, &MainWindow::OnMouseMove);

OnMouseMoveEvent(args);
[/code]

Any tips?

Share this post


Link to post
Share on other sites
wqking    761
Why args is passed by value instead of const reference? (You can still modify a const reference's mutable member).
How do you implement an "all in one" handler function that has EventArgs as parameter but can accept any derived event class?

Sometimes reinventing the wheels may be not bad, you can learn much from it. But if you decide to reinvent, reinvent some featured wheels, so you won't get trouble when your application goes more complicated in the future.
Otherwise, try to find a matured library. Boost::signal(2) is not the only signal/slot library. Libsigc++ is another one, and there are more others.

Share this post


Link to post
Share on other sites
lpcstr    127
[quote name='wqking' timestamp='1305540165' post='4811367']
Why args is passed by value instead of const reference?
[/quote]

It was late and I wrote this up quickly from memory of something I had written once before. I left out the pass by reference by mistake.

[quote name='wqking' timestamp='1305540165' post='4811367']
How do you implement an "all in one" handler function that has EventArgs as parameter but can accept any derived event class?
[/quote]

I'm not sure I understand what you are asking.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this