michelson
michelson

Reputation: 750

std::async with class member function


I'm kind of new to std::async and I have problems understanding how it works. I saw example of how to pass member funcion to std::async somewhere on the web but it seems not to compile. Whats the problem here? How can it be done without lambda?

class Test {
  std::future<void> f;
  void test() {}
  void runTest() {
    // ERROR no instance overloaded matches argument list
    f = std::async(std::launch::async, &Test::test, this); 

    // OK...
    f = std::async(std::launch::async, [this] {test();}); 
  }
  void testRes() {
    f.get();
  }
};

Upvotes: 4

Views: 2444

Answers (1)

Matthias247
Matthias247

Reputation: 10396

You should be able to use std::bind to create a callable function object:

f = std::async(std::launch::async, std::bind(&Test::test, this));

In your example &Test::test is not a function that takes one parameter of type Test, as it would be expected by std::async. Instead it is member function, which must be called differently.

Upvotes: 2

Related Questions