mardi 21 juillet 2015

How to use reference wrapping for a thread involving a member function of user defined class returning a non void type(c++)

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

Aucun commentaire:

Enregistrer un commentaire