C++ 使用std::bind将QTimer::singleShot传递给std::async
以下代码启动非阻塞计时器,该计时器将在1秒后启动函数C++ 使用std::bind将QTimer::singleShot传递给std::async,c++,qt,c++11,stdbind,C++,Qt,C++11,Stdbind,以下代码启动非阻塞计时器,该计时器将在1秒后启动函数myFunc: MyClass.h: std::future<void> timer_future_; 我想用std::functions替换lambda函数。我已成功更换了第二个lambda,如下所示: timer_future_ = std::async( std::launch::async, [this] { QTimer::singleShot(1000,
myFunc
:
MyClass.h:
std::future<void> timer_future_;
我想用std::function
s替换lambda函数。我已成功更换了第二个lambda,如下所示:
timer_future_ = std::async(
std::launch::async,
[this] { QTimer::singleShot(1000,
std::bind(&MyClass::myFunc, this)
);
}
);
现在如何用另一个std::bind()调用替换第一个lambda?
注意,函数QTimer::singleShot
来自Qt库;其文件是。其原型是:
void QTimer::singleShot(int msec, Functor functor)
根据,可以在中找到函子类型的定义。它说:
template <class FunctorT, class R, typename... Args> class Functor { /*...*/ }
对于此代码,MSVC编译器返回了错误消息
error: C2059: syntax error: ')'
在第三行
为什么我不直接使用已经开始工作的lambda呢?答案是简单地尝试使用STD::BUDE(),而不是更多地教我C++语言的各种特性以及如何使用它们。
编辑:实现库巴·奥伯答案的代码:
QTimer::singleShot(1000, [this] {
timer_future_ = std::async(
std::launch::async,
std::bind(&MyClass::myFunc, this)
);
});
计算开始和结束括号并添加分号计时器需要事件循环,并且
std::async
将在没有运行事件循环的工作线程中调用它。我想问你为什么要这么做
如果要在延迟后在工作线程中运行某些内容,请在具有事件循环的线程中运行计时器,并从该计时器启动异步操作。抱歉,输入错误将最后一个括号和分号留在显示我尝试的代码块外。我已经编辑过了。我试图编译的代码中没有这个输入错误。谢谢,你说得对。我试图在不阻塞事件循环的情况下运行计时器。我应该把
async()
调用放在QTimer::singleShot()调用中。我在问题的底部添加了遵循这种方法的工作代码。
error: C2059: syntax error: ')'
QTimer::singleShot(1000, [this] {
timer_future_ = std::async(
std::launch::async,
std::bind(&MyClass::myFunc, this)
);
});