Return Optional value with ?: operator

You can explicitly wrap the some-value return into an std::optional, and fall back on the constexpr std::nullopt for the no-value return.

std::nullopt:

std::nullopt is a constant of type std::nullopt_t that is used to
indicate optional type with uninitialized state.

std::nullopt_t:

std::nullopt_t is an empty class type used to indicate optional type
with uninitialized state. In particular, std::optional has a
constructor with nullopt_t as a single argument, which creates an
optional that does not contain a value.

With this approach, the true clause of the ternary operator call explicitly returns an std::optional with a some-value, so the compiler can deduce the template parameter/wrapped type (in this example: int32_t) from the type of the supplied wrapped value, meaning you needn’t specify it explicitly.

Applied to your example:

return it != map.end() ? std::optional(it->second) : std::nullopt;

// alternatively
return it != map.end() ? std::make_optional(it->second) : std::nullopt;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)