[英]Invoking a function from another class with Boost in c++
I am fairly new to both c++ and the boost library. 我对c ++和boost库都很新。
What I want to do is invoke a method foo
from a class Bar
inside a class Baz
. 我想要做的是从类
Baz
的类Bar
调用方法foo
。 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: foo
函数可能是这样的:
// 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: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. 你需要使用std :: mem_fun_ref来获取一个函子和boost :: bind (或者你的编译器支持
std::bind
)来绑定应该调用该函数的对象来使用它们。
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: 或者不要使用
bind
并让thread
执行绑定:
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. 编辑:我记得错了:你不需要
mem_fun
, boost::bind
支持指向开箱即用成员的指针。
Thanks for the comments addressing the issue. 感谢您对此问题的评论。
boost::thread qux(boost::bind(
&Bar::foo, // the method to invoke
&bar // the instance of the class
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.