views:

209

answers:

3

Hi,

I'm surprised this question wasn't asked before on SO (well, at least I couldn't find it).

Have you ever designed a method-callback pattern (something like a "pointer" to a class method) in C++ and, if so, how did you do it ?

I know a method is just a regular function with some hidden this parameter to serve as a context and I have a pretty simple design in mind. However, since things are often more complex than they seem to, I wonder how our C++ gurus would implement this, preferably in an elegant and standard way.

All suggestions are welcome !

+9  A: 

boost::function for single callback, boost::signal or boost::signals2 when more than one callbacks can be registered, using boost::bind to bind member methods (or adapting the signatures in different ways).

If you have access to a compiler with C++0x/C++11 support it may have std::function and std::bind that are the new standard version of boost::function and boost::bind

David Rodríguez - dribeas
Thanks. Boost is really astonishing. Is there anything this library can't do ?
ereOn
it can't yet bring about world peace. There was a library in development to do this, but the developers couldn't agree on the syntax.
Phil Nash
@Phil - nope, they just started fighting over bracing styles
DVK
@David: It's going to be a few years before I get used to the name C++11. Was just about to ask if you were referring to version 11 of some specific compiler or what you were talking about... ;)
jalf
+2  A: 

Isn't boost::function (in conjunction with boost::bind) elegant enough? This will also keep you away from nasty (yet standard-conforming) implementation details like pointers to members being larger than a void*, which was a problem in a callback library for an older Windows CE system. I'd rather use a well-known library than having to deal with these problems myself.

OregonGhost
"I'd rather use a well-known library than having to deal with these problems myself." I totally agree with that. Just to know, does `boost::function` require me to link with boost or is it "template" based (just like `boost::shared_ptr`) ?
ereOn
@ereOn: I think it's template-based only, since we're using it in a large project and only link to boost::thread. But I don't know for sure.
OregonGhost
It's template based and header only. And if you have a modern compiler you probably have access to `std::tr1::function` (and `std::tr1::bind`) too - no need to wait for C++0x
Phil Nash
ereOn
+2  A: 

A good introduction into callbacks with C++ you can find here. I used this paper as base for an implementation when boost was not an option.

jopa