Reputation: 1475
I need to do conditional behavior.
std::future<int> f = pointer ? std::async(&Class::method, ptr) : 0;
// ... Some code
x = f.get();
So I would like to assign to x result async result of ptr->method()
call or 0 if ptr
is a nullptr
.
Is the code above ok? Can I do anything like that (assign 'int' to 'std::futture'? Or maybe there is a better solution?
Upvotes: 1
Views: 547
Reputation: 217275
You may return also a std::future
for your other case (using different policy):
std::future<int> f = pointer
? std::async(&Class::method, ptr)
: std::async(std::launch::deferred, [](){ return 0;});
Upvotes: 0
Reputation: 141574
You can load a value into the future without using a thread like this:
std::future<int> f;
if ( pointer )
f = std::async(&Class::method, ptr);
else
{
std::promise<int> p;
p.set_value(0);
f = p.get_future();
}
// ... Some code
x = f.get();
But a simpler way to achieve the same goal would be:
std::future<int> f;
if ( pointer )
f = std::async(&Class::method, ptr);
// ... Some code
x = f.valid() ? f.get() : 0;
Upvotes: 2
Reputation: 409176
std::future
have no conversion constructor so your code is not valid (as you would have noticed if you actually tried to compile the code).
What you can do is use a default-constructed future, and then check if it's valid before you use the future.
Upvotes: 3