问题
I'm having trouble making the wait/get future mechanism work with a member function of user defined class returning a non-void type.
I wrote a very simple example below, the reference wrapping inside the instruction
std::future<int> fut = std::async( &BasicClass::funcInt, std::ref(anObject) );
fails at compile time
#include <iostream> // cout
#include <future> // async, future
using std::cout;
using std::async;
using std::future;
class BasicClass
{ public:
int funcInt(){return 119;}
void funcVoid(){cout << "\nvoid funcVoid()";}
};
int main()
{
BasicClass anObject;
std::thread thread1( &BasicClass::funcVoid, std::ref(anObject));
thread1.join();
std::future<int> fut = std::async( &BasicClass::funcInt, std::ref(anObject));
fut.wait();
int a = fut.get();
return 0;
}
The reference wrapping works find for a thread with a member function returning a void type works fine.
std::thread thread1( &BasicClass::funcVoid, std::ref(anObject));
Can you explain the issue?
Thanks
回答1:
The magical pseudo-function INVOKE that std::async
(among other things) uses doesn't handle pointers-to-member paired with reference_wrapper
s. std::thread
is also supposed to use INVOKE
, but libstdc++ (GCC's standard library)'s implementation happens to not choke on this particular combination, due to the way it was implemented. libc++, Clang's standard library, will fail to compile for both.
Until LWG issue 2219's resolution is voted into the working paper and implemented, just use a pointer:
std::async(&BasicClass::funcInt, &anObject);
来源:https://stackoverflow.com/questions/31553262/how-to-use-reference-wrapping-for-a-thread-involving-a-member-function-of-user-d