-2
私は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:
あなたの戻り値の型が知られており、あなたがstd::bind
と
std::function
を使用することができます不変ですされている場合は
#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;
}
私のプログラムはグラフィカルではないので、私はQTimerを使用できません:これは間違っています。 – YSC
'std :: function'を使って、呼び出し側が引数をバインドするようにします。 –
molbdnilo