Return Optional value with ?: operator

Viewed 7434

I often need to use optional type for functions:

std::optional<int32_t> get(const std::string& field)
{
    auto it = map.find(field);
    if (it != map.end()) return it->second;
    return {};
}

Is there a way to return optional value in one line? e.g. this:

std::optional<int32_t> get(const std::string& field)
{
    auto it = map.find(field);
    return it != map.end() ? it->second : {};
}

results in the error

error: expected primary-expression before '{' token
return it != map.end() ? it->second : {};
                                      ^
2 Answers
Related