boost::thread and member function
Hello All, Newbie question, thanks for your patience. I'm trying to pass a member function as the callback in boost::thread. Given this: class my_class { ... void foo(void); ... }; Instincts told me to do this: boost::thread my_thread( std::mem_fun(&my_class::foo) ); That didn't work and I discovered that boost::thread expects a boost::function0<void> instead. Can somebody please help me bridge the gap between std::mem_fun and boost::function0? I'm using gcc 4.1 on Linux and Boost 1.33.1 Cheers, -steve
I'm trying to pass a member function as the callback in boost::thread. Given this:
class my_class { ... void foo(void); ... };
Instincts told me to do this:
boost::thread my_thread( std::mem_fun(&my_class::foo) );
You want to use boost::bind for this. The below should work. my_class *myClassPtr = new my_class; boost::thread my_thread( boost::bind(&my_class::foo, myClassPtr) );
Please use a smart pointer. in class declaration: typedef boost::scoped_ptrboost::thread tThread_Ptr; tThread_Ptr _spThread; in class constructor or wherever: _spThread.reset( new boost::thread( boost::bind( _run , this ))); Regards, Christian
Steven,
Member functions have an implicit this parameter. When you use mem_fun
on void my_class::foo(void), you actually get a unary functor whose
parameter is of type my_class * const.
The boost::bind Matt mentioned sets that parameter, resulting in a
nullary functor. If you use a non-member (or class-static) void()
function, you would not need the bind.
On 7/17/06, Christian Henning
Please use a smart pointer.
Smart pointer is a valid suggestion, but would be more useful for the dynamically-allocated class, than for the boost::thread instance that the OP seems to want on the stack. ~ Scott McMurray
Please use a smart pointer. in class declaration: typedef boost::scoped_ptrboost::thread tThread_Ptr; tThread_Ptr _spThread; in class constructor or wherever: _spThread.reset( new boost::thread( boost::bind( _run , this ))); Regards, Christian
participants (4)
-
Christian Henning
-
King, Steven R
-
Matt Amato
-
me22