Class and std::async on class member in C++

do_rand_stf is a non-static member function and thus cannot be called without a class instance (the implicit this parameter.) Luckily, std::async handles its parameters like std::bind, and bind in turn can use std::mem_fn to turn a member function pointer into a functor that takes an explicit this parameter, so all you need to do is to pass this to the std::async invocation and use valid member function pointer syntax when passing the do_rand_stf:

auto hand=async(launch::async,&A::do_rand_stf,this,i,j);

There are other problems in the code, though. First off, you use std::cout and std::endl without #includeing <iostream>. More seriously, std::future is not copyable, only movable, so you cannot push_back the named object hand without using std::move. Alternatively, just pass the async result to push_back directly:

ran.push_back(async(launch::async,&A::do_rand_stf,this,i,j));

You can pass the this pointer to a new thread:

async([this]()
{
    Function(this);
});

Tags:

C++

C++11