How to use boost bind with a member function

hamishmcn picture hamishmcn · Feb 21, 2010 · Viewed 113.3k times · Source

The following code causes cl.exe to crash (MS VS2005).
I am trying to use boost bind to create a function to a calls a method of myclass:

#include "stdafx.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <functional>

class myclass {
public:
    void fun1()       { printf("fun1()\n");      }
    void fun2(int i)  { printf("fun2(%d)\n", i); }

    void testit() {
        boost::function<void ()>    f1( boost::bind( &myclass::fun1, this ) );
        boost::function<void (int)> f2( boost::bind( &myclass::fun2, this ) ); //fails

        f1();
        f2(111);
    }
};

int main(int argc, char* argv[]) {
    myclass mc;
    mc.testit();
    return 0;
}

What am I doing wrong?

Answer

Georg Fritzsche picture Georg Fritzsche · Feb 21, 2010

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.