Which way to handle events?

G

Glen Able

Hello

I'm currently writing some library code and I want to allow certain events
to be handled by whatever app is using this library. E.g. responding to
error messages by printing them/logging them to a file/whatever.

I can see two good options:

1) Hold a function ptr which can be set by the application to point to one
of its (presumably static?) methods.

2) Hold a ptr to an object of some sort of 'handler' class, so the app can
derive its own type from this and override the virtual methods. This could
be an abstract base class, or possibly could have default empty
implementations of the methods.

Anyone have any thoughts about which of these various possibilities would be
preferable, or even come up with something better?

thanks!
G.A.
 
I

Ivan Vecerina

Glen Able said:
I'm currently writing some library code and I want to allow certain events
to be handled by whatever app is using this library. E.g. responding to
error messages by printing them/logging them to a file/whatever.

I can see two good options:

1) Hold a function ptr which can be set by the application to point to one
of its (presumably static?) methods.

2) Hold a ptr to an object of some sort of 'handler' class, so the app can
derive its own type from this and override the virtual methods. This
could
be an abstract base class, or possibly could have default empty
implementations of the methods.

Anyone have any thoughts about which of these various possibilities would
be
preferable, or even come up with something better?

Your option 2) is the most straightforward, and is the best
choice in some cases.

Plain function pointers (as in 1) are error prone, and are best avoided.
They could be replaced by function objects (i.e. a callback to a method
of a specific objects), such as those in boost::function. See:
http://www.boost.org/doc/html/function.html
Such a callback template is expected to be part of the standard library
in the next C++ standard.

Alternatively, depending on circumstances, using another design pattern
such as Observer-Listener, might be a better choice...


Cheers,
Ivan
 
J

Jesper Madsen

When looking at boost as Ivan suggests, try looking at boost/signal.
That is a great way to implement events...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top