c++ - 在类中调用异步函数
问题描述
我有这个类有一些方法。其中之一需要在广泛的数据(坐标)上计算和渲染某些东西。为了让程序运行得更快更流畅,我想到了使用异步方法。我创建了一个进行计算和渲染的私有函数。
我的课:
#include <future>
class MyClass {
public:
// there's a constructor with all the class' variable-declarations and such that I will omit here
void draw() {
for(int i(0); i < width; ++i) {
for(int j(0); j < width; ++j) {
std::async(compute_and_render, i, j);
}
}
}
private:
void compute_and_render(int x, int y) {
// does some computations and rendering
}
}
我的编译器(MinGW)说error: reference to non-static member function must be called
。我也尝试将函数async
作为指针传递,但没有取得多大成功。
解决方案
std::async
需要调用函数,方法不是函数,因为它必须在对象上调用。如何std::async
知道要调用哪个对象compute_and_render
?
试试这个,它使用 lambda 函数来捕获对象
std::async([this](int ii, int jj) { compute_and_render(ii, jj); }, i, j);
请注意我没有经验,std::async
所以我不知道这是否明智,但我确实知道如何编写 lambda 函数。
推荐阅读
- reactjs - 由顶级 BrowserRouter 调用的组件内部的 BrowserRouter 与 NavLinks 不同步
- javascript - 构建捆绑包:构建捆绑包文件时出错->文件'root/res/drawable/sr_list_item_background.xml'使用保留文件或目录名称'res'
- r - Data Wrangling - R - 想要删除在 fyweek 和 launchweek 之间对应的行
- r - r dplyr 文本挖掘 eval(rhs,env,env)中的错误:找不到对象'score'
- git - WebStorm JetBrains IDE 使用错误的 GitHub 帐户推送代码,给我一个 403 禁止错误
- c# - 澄清对这个条件的理解
- python - 如何从 pyspark 中的 MLP 管道模型中获得最佳超参数?
- python - 获取与标签对应的行,对于许多标签
- javascript - jsPDF addImage 在 IE11 中不支持文件类型“UNKNOWN”
- r - 为什么我在数据框中分隔行时遇到问题?