Class member function with argument run asynchronously

62 Views Asked by At

I am trying to asynchronously run a member function, but I seem to have issues with every attempt. Here is my code example:

A::A(){}
A::~A(){}
void A::asyncFunc(int i)
{
    std::cout<< i ;
}

void A::otherFunc()
{
    std::future<void> t;
    for(int i = 0; i<bigNumber; i++)
    {
        t = std::async(std::launch::async, &A::asyncFunc, this, i); // Problem code line
    }
}

With this code I'm being prompted with: "No instance of overloaded function std::async matches the argument list".

t = std::async(std::launch::async, static_cast<void(A::*)(int)>(&A::asyncFunc), this, i);

Same issue with explicitly casting it. So I thought that maybe I can try lambdas.

t = std::async(std::launch::async, [=](){ asyncFunc(i); });
t = std::async(std::launch::async, [=](){ &A::asyncFunc(i); });

But this time I'm prompted with: "An enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list".

Do you know what I'm doing wrong in both cases?

0

There are 0 best solutions below