Invoking a function from another class with Boost in c++
I am fairly new to both c++ and the boost library.
What I want to do is invoke a method foo
from a class Bar
inside a class Baz
. Here is basically what I want to achieve:
Baz::doSomething() {
Bar bar;
boost::thread qux(bar.foo);
}
And the foo
function could be something like:
// bar.cpp
void foo() {
const int leet = 1337; // Very useful
}
However, when I try to compile it tells me that:
error: no matching function for call to ‘boost::thread::thread(<unresolved overloaded function type>)’
/usr/local/include/boost/thread/detail/thread.hpp:215:9: note: candidates are: boost::thread::thread(boost::detail::thread_move_t<boost::thread>)
/usr/local/include/boost/thread/detail/thread.hpp:201:18: note: boost::thread::thread(F, typename boost::disable_if<boost::is_convertible<T&, boost::detail::thread_move_t<T> >, boost::thread::dummy*>::type) [with F = void (Snake::*)(), typename boost::disable_if<boost::is_convertible<T&, boost::detail::thread_move_t<T> >, boost::thread::dummy*>::type = boost::thread::dummy*]
/usr/local/include/boost/thread/detail/thread.hpp:154:9: note: boost::thread::thread()
/usr/local/include/boost/thread/detail/thread.hpp:122:18: note: boost::thread::thread(boost::detail::thread_data_ptr)
/usr/local/include/boost/thread/detail/thread.hpp:113:开发者_JAVA技巧9: note: boost::thread::thread(boost::thread&)
What am I missing here?
Member functions are different from free functions.
You need to use std::mem_fun_ref to get a functor and boost::bind (or std::bind
should your compiler support it) to bind the object on which the function should be called on to use them.
The end result should look something like this:
boost::thread qux(boost::bind(&Foo::bar, bar)); // makes a copy of bar
boost::thread qux(boost::bind(&Foo::bar, &bar)); // make no copy of bar and calls the original instance
Or don't use bind
and let thread
do the binding:
boost::thread qux(&Foo::bar, &bar);
Edit:
I remembered wrong: You don't need mem_fun
, boost::bind
supports pointers to members out of the box.
Thanks for the comments addressing the issue.
boost::thread qux(boost::bind(
&Bar::foo, // the method to invoke
&bar // the instance of the class
));
精彩评论