我使用的是c ++ 11,因为我的程序不是图形化的,所以我不能使用QTimer。
我不明白如何使用参数存储我的指针函数,并在我的run方法中调用此函数。
感谢您的帮助。
timer.h:
#ifndef TIMER_H
#define TIMER_H
#include <atomic>
#include <thread>
#include <chrono>
#include <iostream>
#include <list>
using namespace std;
class Timer {
private:
atomic_bool done_ {};
thread worker_{};
//time interval
chrono::milliseconds time;
void run_();
Fn** fn; // function called
Args** args; // Argument of this function
public:
template <class Fn, class... Args>
Timer(chrono::milliseconds time, Fn&& fn, Args&&... args);
~Timer();
};
#endif // TIMER_H
timer.cpp:
#include "timer.h"
template <class Fn, class... Args>
Timer::Timer(chrono::milliseconds time,Fn&& fn, Args&&... args){
this->time = time;
this->fn = fn;
this->args = args;
worker_ = thread(&Timer::run_,this);
}
// Thread method
void Timer::run_(){
while(!this->done_.load()){
//call function
this_thread::sleep_for(time);
}
}
Timer::~Timer(){
done_.store(true);
if(worker_.joinable())
worker_.join();
else
cout << "thread termined" << endl;
}
答案 0 :(得分:0)
如果您的退货类型已知并且不变,则可以使用std::bind
和std::function
。要将可调用对象与args
一起存储,请使用std::bind
。但是您需要一个通用结构来存储std::bind
和std::function
的结果。
在您的班级中声明std::function<void()>
并初始化它:
template <class Fn, class... Args>
Timer::Timer(chrono::milliseconds time, Fn&& fn, Args&&... args){
static_assert(std::is_same_v<std::result_of_t<Fn(Args...)>, void>, "Return type must be void");
this->time = time;
auto callable = std::bind(fn, std::forward<Args>(args)...);
this->func = std::function<void()>(callable);
worker_ = thread(&Timer::run_,this);
}