-1

How can I pass an object to a function which is started asynchronously?

#include <future>
#include <thread>

class SomeObject
{
    void Dummy();
}

class A
{
    public:
      void Test1();
      void Test2(SomeObject o);
      void Test3(SomeObject &o);
}      

A a;
auto a = std::async(std::launch::async, &A::Test1, a);  // OK

SomeObject o;
auto b = std::async(std::launch::async, &A::Test2, a, o);  // ERROR
auto c = std::async(std::launch::async, &A::Test3, a, std::ref(o));  // ERROR

The function T1 is launched without error. The Test2 and Test3 need an object argument, but I get and error: No instance of overloaded function std::async matches the argument list.

query
  • 329
  • 7
  • 18
  • Please post [mcve]. Currently you have *error: redefinition of 'a'* and many syntax errors. – 273K Mar 08 '19 at 03:45

2 Answers2

1

It may be helpful to include fuller code. For example, I see a few problems right away:

  • Your class declarations aren't followed by a semicolon after the closing brace
  • You are redefining the variable 'a'

The following corrected code compiles without error in VS 2017 (no c++17 needed):

#include <future>
#include <thread>

class SomeObject
{
    void Dummy();
};

class A
{
public:
    void Test1();
    void Test2(SomeObject o);
    void Test3(SomeObject &o);
};

void func()
{
    A a;
    auto d = std::async(std::launch::async, &A::Test1, a);  // OK

    SomeObject o;
    auto b = std::async(std::launch::async, &A::Test2, a, o);  // OK
    auto c = std::async(std::launch::async, &A::Test3, a, std::ref(o));  // OK
}
0

the code in the snipped show error, there are missing semicolon at the end of the class declaration. and it compile without error in g++ version 7.3

Aneury Perez
  • 82
  • 2
  • 5