我已经整理了一个简单的c ++计时器类,它应该定期从SO上的各种示例调用给定的函数,如下所示:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class CallBackTimer
{
public:
CallBackTimer()
:_execute(false)
{}
void start(int interval, std::function<void(void)> func)
{
_execute = true;
std::thread([&]()
{
while (_execute) {
func();
std::this_thread::sleep_for(
std::chrono::milliseconds(interval));
}
}).detach();
}
void stop()
{
_execute = false;
}
private:
bool _execute;
};
Run Code Online (Sandbox Code Playgroud)
现在我想从C++类中调用它,如下所示
class Processor()
{
void init()
{
timer.start(25, std::bind(&Processor::process, this));
}
void process()
{
std::cout << "Called" << std::endl;
}
};
Run Code Online (Sandbox Code Playgroud)
但是,这会调用错误
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
Run Code Online (Sandbox Code Playgroud) 我想知道我们如何制作一个循环(例如,while 循环),其中 while 循环内的语句是基于时间的。
更清楚地说,例如我想制作一个while循环,我将每10秒输入一次。
伪代码如下:
while (10 seconds have passed)
{
//do Something
}
Run Code Online (Sandbox Code Playgroud)
那么,如何使上述伪代码成为现实呢?(我希望已经清楚了)