2012-08-01 50 views
5

是否使用STL實現了TimerCallback庫?我無法將Boost依賴項引入到我的項目中。基於標準模板的TimerCallback函數LIbrary without Boost

到期的計時器應該能夠回調註冊的功能。

+1

海事組織,而不是引入一個庫,你可能能夠快速,乾淨地編寫自己的計時器。產生一個新的線程,反覆調用你的函數,然後使線程休眠一段時間。 – SuperSaiyan 2012-08-01 16:48:48

回答

8

有標準庫沒有具體的計時器,但它是很容易實現一個:利用

#include <thread> 

template <typename Duration, typename Function> 
void timer(Duration const & d, Function const & f) 
{ 
    std::thread([d,f](){ 
     std::this_thread::sleep_for(d); 
     f(); 
    }).detach(); 
} 

例子:

#include <chrono> 
#include <iostream> 

void hello() {std::cout << "Hello!\n";} 

int main() 
{ 
    timer(std::chrono::seconds(5), &hello); 
    std::cout << "Launched\n"; 
    std::this_thread::sleep_for(std::chrono::seconds(10)); 
} 

要注意的是在功能上的另一個線程調用,所以確保它訪問的任何數據都得到適當的保護。

+0

不錯的解決方案謝謝你,但是,這隻適用於'clang',g ++ 4.8.2說'error:field'timer(const Duration&,const Function&)[with Duration = std :: chrono :: duration ; Function = void()] :: __ lambda0 :: __ f'無效聲明函數類型'。有任何想法嗎? – Avio 2014-12-09 12:59:37

+0

@Avio:將參數改爲'&hello',強制轉換爲指針類型。 (我不確定Clang或GCC是否在這裏正確地推斷出這種類型,但是這應該使得兩者都能做到你想要的)。 – 2014-12-09 13:07:05