You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@qpid.apache.org by Alan Conway <ac...@redhat.com> on 2007/11/05 17:02:09 UTC

C++: note on use of boost::function vs. template functions.

boost::function is a handy way to store arbitrary function objects BUT
it does so at the cost of a heap allocation. This may well be justified
if you only pass the function during some "setup" and not for every
message processed but be careful.

Note however that if you simply want to PASS an arbitrary functor there
is a more efficient and equally convenient way to do it:

instead of:
 void doSomething(boost::function<X(Y,Z)> withFunction) { 
   blah; withFunction(y,z); ....

Do:
 template <class Functor> void doSomething(Functor withFunction) {
   blah; withFunction(y,z); ....

The second version takes any functor and uses a copy constructor to copy
it on stack instead of heap. You can't pass a function pointer directly
to the second version, but you can simply wrap it in boost::bind, i.e.
instead of 
 doSomething(myFunction);
do
 doSomething(boost::bind(myFunction, _1, _2)

This makes your API equally flexible but without any imposed performance
penalty, and of course if you want you can still use boost::function
*internally* as a handy way to store the functor for future use.

Cheers,
Alan