我使用一個包裝類各地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