1

我正在做一个优化项目,并决定尝试使用线程来提高我的代码速度。代码的格式是:

主要.cpp:

int main(int argc, char **argv) {
    B *b = new B(argv[1]);
    b->foo();
    delete b;
    return EXIT_SUCCESS;
}

B.cpp:

#include B.hpp

B::B(const char *filename) { .... }

B::task1(){ /*nop*/ }

void B::foo() const { 
    boost::thread td(task1);
    td.join();
}

B.hpp:

#include <boost/thread.hpp>

class B{
    public:
    void task1();
    void foo();
}

但是,当我尝试编译此代码时,出现错误boost::thread td(task1),说:

error: no matching function for call to 'boost::thread::thread(<unresolved overloaded function type>)'

不完全确定问题出在哪里,我尝试破解但没有成功。任何帮助表示赞赏!

编辑:新错误

B.o: In function 'B::b() const':
B.cpp:(.text+0x7eb): undefined reference to 'vtable for boost::detail::thread_data_base'
B.cpp:(.text+0x998): undefined reference to 'boost::thread::start_thread()'
B.cpp:(.text+0x9a2): undefined reference to 'boost::thread::join()'
B.cpp:(.text+0xa0b): undefined reference to 'boost::thread::~thread()'
B.cpp:(.text+0xb32): undefined reference to 'boost::thread::~thread()'
B.o: In function 'boost::detail::thread_data<boost::_bi::bind_t<void, boost::_mfi::cmf0<void, B>, boost::_bi::list1<boost::_bi::value<B const*> > > >::~thread_data()':
B.cpp:(.text._ZN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi4cmf0Iv4BEENS2_5list1INS2_5valueIPKS6_EEEEEEED2Ev[_ZN5boost6detail11thread_dataINS_3_bi6bind_tIvNS_4_mfi4cmf0Iv4BEENS2_5list1INS2_5valueIPKS6_EEEEEEED5Ev]+0x8): undefined reference to 'boost::detail::thread_data_base::~thread_data_base()'
4

1 回答 1

3

B::task()是一个成员函数,所以它需要一个隐式类型的第一个参数B*。因此,您需要将实例传递给它才能在boost::thread.

void B::foo() const { 
  boost::thread td(&B::task1, this); // this is a const B*: requires task1() to be const.
  td.join();
}

但既然B::foo()是一种const方法,你也必须制作B::task1()一个const方法:

class B {
  void task1() const:
}
于 2013-03-05T20:23:53.770 回答