Calling an async function inside a class

Viewed 176

I have this class with a few methods. One of them needs to compute and render something over a wide range of data (coordinates). To make the program run faster and smoother, I thought of using async methods. I created a private function that does the computation and rendering.

My class:

#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
    }
}

My compiler (MinGW) says error: reference to non-static member function must be called. I also tried passing the function to async as a pointer without much success.

1 Answers

std::async requires a function to call, a method is not a function because it must be called on an object. How is std::async going to know which object to use to call compute_and_render?

Try this which uses a lambda function to capture the object

 std::async([this](int ii, int jj) { compute_and_render(ii, jj); }, i, j);

Please note I have no experience with std::async so I don't know if this is a sensible thing to do or not, but I do know how to write a lambda function.

Related