我目前正在创建像这样的boost :: threads:
boost::thread m_myThread; //member variable
//...
m_myThread = boost::thread(boost::bind(&MyClass::myThreadFunction, this));
这将启动一个执行成员函数“myThreadFunction”的线程。
我想封装一个新线程的开头并使用像
这样的东西boost::thread m_myThread; //member variable
//...
startAThread(&m_myThread, boost::bind(&MyClass::myThreadFunction, this), 123 /*some int argument*/);
我以为我可以像这样实现“startAThread”:
namespace internal
{
template <typename Callable>
void threadhelper(Callable func, int x)
{
doSomething(x);
func();
}
}
template <typename Callable>
void startAThread(boost::thread* threadToCreate, Callable func, int x)
{
*threadToCreate = boost::thread(boost::bind(internal::threadhelper<Callable>, func, x));
}
但是,无法使用
进行编译usr/include/boost/bind/bind.hpp: In member function 'void boost::_bi::list2<A1, A2>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = void (*)(boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, int), A = boost::_bi::list0, A1 = boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, A2 = boost::_bi::value<int>]':
usr/include/boost/bind/bind_template.hpp:20: instantiated from 'typename boost::_bi::result_traits<R, F>::type boost::_bi::bind_t<R, F, L>::operator()() [with R = void, F = void (*)(boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, int), L = boost::_bi::list2<boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, boost::_bi::value<int> >]'
usr/include/boost/thread/detail/thread.hpp:61: instantiated from 'void boost::detail::thread_data<F>::run() [with F = boost::_bi::bind_t<void, void (*)(boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, int), boost::_bi::list2<boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >, boost::_bi::value<int> > >]'
MyClass.cpp:160: instantiated from here
usr/include/boost/bind/bind.hpp:313: error: conversion from 'void' to non-scalar type 'boost::_bi::bind_t<void, boost::_mfi::mf0<void, MyClass>, boost::_bi::list1<boost::_bi::value<MyClass*> > >' requested
这个错误是什么意思?代码有什么问题?
非常感谢!
答案 0 :(得分:1)
尝试
namespace internal
{
template <typename Callable>
void threadhelper(Callable func, int x)
{
doSomething(x);
func();
}
}
template <typename Callable>
void startAThread(boost::thread& threadToCreate, Callable func, int x) {
threadToCreate = boost::thread(boost::bind(&internal::threadhelper<Callable>, func, x));
}
我也使用了引用而不是指针。