I'm so sick of the pass-callback-data-as-void*-struct anti-pattern. Boost bind solves it nicely, but is an unacceptable dependency. What's a lightweight alternative? How would I write it myself as simply as possible?
-
Could you give an example of how you're using boost::bind, so we can see the inefficiency that you're trying to solve?– Drew DormannCommented Dec 19, 2008 at 16:51
-
1Boost bind is not "heavy" in any definition of the word that I've come across. Could you explain what you mean by that?– MarcinCommented Dec 19, 2008 at 21:22
-
@Marcin, It is most definitely too heavy for certain domains where every microsecond matters. Particularly in the cases where you have to pass the resulting closure outside its creation context and the compiler can't optimize it out when it's called.– Alex BCommented Nov 30, 2010 at 3:08
7 Answers
First, I question your assertion that it's far too heavy for you to use.
Second, roll your own template, if you need to control the behavior.
Third, if you're afraid of rolling your own template, I question your ability to judge that boost::bind
is too heavy for you to use.
-
I agree, especially when you consider compiler optimizations. Those will alleviate much of the perceived "weightiness" of boost::bind.– BrianCommented Dec 19, 2008 at 22:27
-
@Brian Depends on the context. In cases where the call site is different to the construction site, the compiler won't be able to optimize most of it. In fact you are likely to have it stored in
boost::function
, which adds to the overhead.– Alex BCommented Nov 30, 2010 at 3:12
Check out the fast delegate by Don Clugston. It's supposedly the fastest delegate you can find on most current platforms (compiles down to 2 assembly instructions.) Version 1.4+ gains some Boost.Bind compatibility.
I'm not familiar with boost:bind, but is it something like this?
#include <iostream>
void foo (int const& x) {
std::cout << "x = " << x << std::endl;
}
void bar (std::string const& s) {
std::cout << "s = " << s << std::endl;
}
template<class T>
void relay (void (*f)(T const&), T const& a) {
f(a);
}
int main (int argc, char *argv[])
{
std::string msg("Hello World!");
relay (foo, 1138);
relay (bar, msg);
}
Output --
x = 1138
s = Hello World!
-
Not quite. If relay() returned an object that had operator(), and invoking that then called foo(1138) or bar(msg), then you'd be closer to Boost.Bind. All you've done is a simple callback mechanism. Commented Dec 19, 2008 at 20:30
-
thats all the start I need, I can do the functor part myself. Commented Dec 19, 2008 at 22:29
Boost.Function improved performance dramatically as of around 1.34 when used together with boost::bind. If you profiled with an old boost version, maybe do it again with a more recent one. boost::function
got the ability to save small function objects in a small buffer allocated on the stack, instead of on the heap (using placement new).
See this mailing list message: http://lists.boost.org/Archives/boost/2006/01/98993.php.
A common C++ idiom is to use functors (i.e. objects that override operator()). The point is that you use a single object to encapsulate both the code to be called back, and the data on which that code will act. Whether the functor is hand-rolled, or generated using boost::bind and/or <functional>, probably doesn't make a whole lot of difference to runtime overhead.
So instead of:
typedef void (*cb)(void*);
void funcThatNeedsCallback(cb thecallback, void *thedata) {
// blah blah
thecallback(thedata);
}
do:
template<typename T>
void funcThatNeedsCallback(T &thefunctor) {
// blah blah
thefunctor();
}
Then the caller does:
struct MyFunctor {
int mydata1;
char *mydata2;
void operator()(void) {
// do something with mydata1 and mydata2
}
};
MyFunctor mf = { value1, value2 };
funcThatNeedsCallback(mf);
Obviously if you prefer, you can make the members private and pass them in to a constructor rather than using the initializer list.
If you're worried about templates (for instance, if funcThatNeedsCallback is a lot of code which gets duplicated), then use an abstract class to define a virtual method which the parameter must have, and use that method as the callback:
class CallbackInterface {
virtual void theCallback(void) = 0;
virtual ~CallbackInterface() {} // just in case
};
void funcThatNeedsCallback(CallbackInterface &cb) {
// blah blah
cb.theCallback();
}
There is libsigc++. The license is LGPL, but the implementation is about what Boost.Signal does (I'm reading "too heavyweight" to mean "installing all of Boost is too heavyweight" not "Boost.Signal is too slow").
-
This looks really useful. However, by "heavyweight", I think the original poster meant CPU time. Does libsigc++ run faster?– VorticoCommented Oct 25, 2012 at 1:26
-
@Vortico: To be honest, I don't have any idea whether either library runs significantly faster than the other. I remember when I looked at the implementations years ago that the libraries' internals were remarkably similar, so I would be amazed if there were a performance difference. I can say that I've never noticed a pause between clicking on a UI element and getting a response using either library; so (for me) they're both "fast enough." Commented Oct 25, 2012 at 17:33
-
Although my implementation with almost certainly be different than others', I found libsigc++ to be about 10x slower than Boost bind/functions when repeatedly calling a callback function. (I need to call the callback about 100 million times a second, so I should probably redesign to call raw pointers.)– VorticoCommented Oct 26, 2012 at 5:27
-
@Vortico: You may even be able to avoid the overhead of a function pointer ( hpl.hp.com/techreports/92/HPL-92-65.html ): "[U]sing [functors] not only avoids the overhead of an indirect function call (as occurs when a pointer to a function is passed), it even eliminates the cost of a direct call" (pg. 7). I suspect that lambdas have the same properties as far as the compiler's optimizer is concerned. However, since I never have to worry about this level of performance, I'm probably not the right person to take advice from. Commented Oct 26, 2012 at 8:45
People defending boost::binds speed have probably never written low latency trading systems or high speed graphics libraries.
Boost is a good general purpose library, not a speed optimised one. Some boost libraries (compared to tuned implementations) can be quite slow in comparison.
For functions/delegates, See http://www.codeproject.com/KB/cpp/fastdelegate2.aspx for a useful comparison.
Ciao.