0

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?

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
Zefelix
  • 13
  • 4
  • Your code works fine for me: https://godbolt.org/z/E3bMWsKP3 – paddy Dec 07 '22 at 10:58
  • 1
    Please [edit] your question to provide a [mcve]. I don't see anything obviously wrong with the code shown other than the use of undeclared `bigNumber` and missing headers. Although, note that re-assigning to `t` in the loop will cause the the existing `std::future` to be destroyed with the associated [blocking behaviour](https://en.cppreference.com/w/cpp/thread/future/~future). – G.M. Dec 07 '22 at 11:01
  • @G.M. You guys are right. I'm having the code underlined with the displayed messages mentioned in the post, but it didn't even pass my mind to run it... I don't understand why they are underlined though as being wrong – Zefelix Dec 07 '22 at 11:21
  • *"I don't understand why they are underlined though as being wrong"* Odd as it seems, the editor might be using a differnt compiler for the code checks. Not the one you then use to build the executable. – BoP Dec 07 '22 at 11:31
  • Interactive error checking ("IntelliSense") of C++ is notoriously unreliable. Treat them as "to the best of my knowledge, but I could be wrong" guesses. (I personally switch them off.) – molbdnilo Dec 07 '22 at 12:49

0 Answers0