Member function as first class function
将成员函数作为first class function。
stackoverflow Class and std::async on class member in C++
NOTE: 演示了两种典型的写法
NOTE:
std::async内部使用std::invoke,参见Callable章节;
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));
NOTE: 使用lambda
You can pass the this pointer to a new thread:
async([this]()
{
Function(this);
});
reddit What is the proper way to pass a member function to std::async?
方式总结
使用std::function + lambda
参见std::function章节。
使用lambda
[this]
{
this->member_function();
}
使用pointer to member function
参见Pointer-to-member-function。
使用std::mem_fn
使用ca llable std::invoke
就像 stackoverflow Class and std::async on class member in C++ # A 中所描述的方式;
TODO
stackexchange C++ member function wrapper for interfacing with C APIs
stackexchange Simple wrapper for member function pointers with known signature