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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With