0

I wish to instantiate public members of a class and return it as a promise.
This is what I am trying to do:

class A
{
public:
   int x;
};

std::future<A> returnPromiseA(int y)
{
   std::promise<A> promise;
   promise.x = y; //<- THIS IS INCORECT
   return promise;
}

promise.x = y; is an incorrect syntax.
What is the correct syntax for assignment?

Bilal Siddiqui
  • 349
  • 3
  • 17
JayHawk
  • 275
  • 1
  • 5
  • 15

2 Answers2

2

You can't access the members of the template type through a std::promise. To set the value in a std::promise you need to use the set_value function.

That means you code should look like

std::future<A> returnPromiseA(int y)
{
   std::promise<A> promise;
   promise.set_value(A{y}); // construct an A with the desired value and set promises' value to that
   return promise;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

Current C++ async classes cannot chain continuations so you'll have to do it other way:

std::future<A> returnFutureA(int y) {
    return std::async([y]{ A retVal; retVal.x = y; return retVal; });
}
bipll
  • 11,747
  • 1
  • 18
  • 32
  • Thank you! If I wish to read the members of a function which returns a future. How would I do it? – JayHawk Aug 20 '18 at 18:28
  • They are deep encapsulated in the function deeply encapsulated in `async`'s return value. If you want to keep track of construction arguments you used to create an async value, well, guess it can't be helped, you'll have to define a wrapper struct that, when constructed, creates a future and reports it readily but still remembers the arguments—and additionally allows to `set` them, changing the async value respectively, if that's what you mean. – bipll Aug 20 '18 at 18:36