2017-01-20 5 views
-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::bindstd::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; 

} 
+3

私のプログラムはグラフィカルではないので、私はQTimerを使用できません:これは間違っています。 – YSC

+0

'std :: function 'を使って、呼び出し側が引数をバインドするようにします。 – molbdnilo

答えて

0

。呼び出し可能オブジェクトをargsと共に格納するには、std::bindを使用します。しかし、あなたはstd::bindstd::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); 
} 

std::bindstd::functionをお読みください。

関連する問題