Scott Langham Scott Langham - 4 months ago 12
C++ Question

In C++17 can an if statement with an initializer be used to unpack an optional?

I'm writing some code using std::optional's and am wondering if C++17's 'if statements with initializers' will be able to help unpack values?

std::optional<int> optionalInt = GetOptionalInt();

I'm making up the function Unpack here:

if( auto [value, has_value] = optionalInt.Unpack(); has_value )
// Use value here.

But, my question is. Will C++17 'if expressions with initializers' help here? If so, how would it be coded?


There is not, and cannot possibly be, such an Unpack() function.

But you could certainly do:

if (std::optional<int> o = GetOptionalInt(); o) {
    // use *o here

though the extra o check is kind of redundant.

This is one of those places where it'd be nice if optional<T> modeled a container of at most one element, so that you could do:

for (int value : GetOptionalInt()) {
    // possibly not entered

but we don't have that interface.