我想定期執行一個以物件為引數的函式。
我嘗試了這個答案:https ://stackoverflow.com/a/72226772/13798537以周期性間隔呼叫一個函式,該函式以整數作為引數,但我不知道如何以周期性間隔呼叫一個函式物件作為論據。
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <memory>
#include <atomic>
#include "window.h" // Contains the declaration of Window class
using cancel_token_t = std::atomic_bool;
template<typename Fnc>
void set_interval(Fnc fun, std::chrono::steady_clock::duration interval,
std::shared_ptr<cancel_token_t> cancel_token=nullptr)
{
std::thread([fun=std::move(fun), interval, tok=std::move(cancel_token)]()
{
while (!tok || !*tok) // Call until token becomes true (if it is set)
{
auto next = std::chrono::steady_clock::now() interval;
fun();
std::this_thread::sleep_until(next);
}
}).detach();
}
void foo(Window &window)
{
// Do something with the window object
}
int main()
{
Window window;
using namespace std::chrono_literals;
auto cancel = std::make_shared<cancel_token_t>(false);
// Ordinary rules for lambda capture apply so be careful
// about lifetime if captured by reference.
set_interval([window]
{
foo(window);
}, 1000ms, cancel);
//set_interval([window]{foo(window);}, 1000ms); // Without token, runs until main exits.
std::this_thread::sleep_for(3s);
*cancel = true;
}
編譯時出現以下錯誤:
'void foo(Window &)': cannot convert argument 1 from 'const Window' to 'Window &'
我怎樣才能做到這一點?
謝謝。
uj5u.com熱心網友回復:
operator()不可變的 lambda 是const. 當您通過副本捕獲時,您無法改變捕獲的“成員”。
您可能希望通過參考來捕獲:
set_interval([&window] { foo(window); }, 1000ms, cancel);
或者,如果您真的想要復制,請制作 lambda mutable:
set_interval([window] mutable { foo(window); }, 1000ms, cancel);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472980.html
下一篇:有問題理解fork()層次樹
