我使用一个包装类各地std::thread
,它是使用计时器结构(基于boost::asio
)一些代码,调用methodToCallEachIteration()
每5000毫秒:C++ lambda,没有看到函数和参数?
class OurThreadWrapperClass{
OurThreadWrapperClass(boost::asio::io_service& = generic_timer_queue_s());
};
class A {
A() : thread1(_TimerIOService){
thread1.setInterval(5000);
// This sets the callback function, to be called every INTERVAL ms.
thread1.start([this](OurThreadWrapperClass&) {
this->methodToCallEachIteration();
});
}
void callAFunctionHere(std::bitset<10> arg) {
// ...
}
void methodToCallEachIteration() {
// ...
}
struct TimerService {
constexpr static const size_t num_threads{2};
TimerService(){
for(auto& t: _threads){
t = std::thread([this](){
boost::asio::io_service::work keepalive{_ioservice};
callAFunctionHere(_anArgument); // The method and arg not recognised
(void)keepalive;
_ioservice.run();
});
}
}
operator boost::asio::io_service&() {
return _ioservice;
}
boost::asio::io_service _ioservice{num_threads};
std::thread _threads[num_threads];
};
OurThreadWrapperClass thread1;
TimerService _TimerIOService;
std::bitset<10> _anArgument;
};
我遇到的问题是,我想从准备线程的TimerService中调用callAFunctionHere()
。我无法在TimerService中移动此函数。然而,编译器抱怨说,它无法找到callAFunctionHere()
或_anArgument
:
error: cannot call member function callAFunctionHere(std::bitset<10>) without object
error: 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = TimerService::TimerService()::__lambda19; _Args = {}]', declared using local type TimerService::TimerService()::__lambda19', is used but never defined [-fpermissive]
thread(_Callable&& __f, _Args&&... __args)
我想我需要改变A::A()
拉姆达这样编译器可以“看到”的方法和说法,但我不太知道如何?
[如何对指到封闭实例-from-c-inner-class](http://stackoverflow.com/questions/6198224/how-to-refer-to-enclosing-instance-from-c-inner-class) –
你可能想重新考虑你的封装这里。 “A”和“TimerService”的功能似乎很混乱,如果意图是为了使TimerService中的功能可以在其他类中重用,而不是使它成为嵌套类“A”,那么似乎是多余的。 – kfsone
BTW'thread1'是在'_TimerIOService'之前构建的,因此您将未初始化的对象传递给'thread1'的构造函数。 – Oktalist