peter55555
peter55555

Reputation: 1475

Conditional std::future and std::async

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

Answers (3)

Jarod42
Jarod42

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

M.M
M.M

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

Some programmer dude
Some programmer dude

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

Related Questions