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::nulloptis a constant of typestd::nullopt_tthat is used to
indicate optional type with uninitialized state.…
std::nullopt_t:
std::nullopt_tis an empty class type used to indicate optional type
with uninitialized state. In particular,std::optionalhas a
constructor withnullopt_tas 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;