首页 > 解决方案 > 在类中调用异步函数

问题描述

我有这个类有一些方法。其中之一需要在广泛的数据(坐标)上计算和渲染某些东西。为了让程序运行得更快更流畅,我想到了使用异步方法。我创建了一个进行计算和渲染的私有函数。

我的课:

#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作为指针传递,但没有取得多大成功。

标签: c++asynchronous

解决方案


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 函数。


推荐阅读