FindOrNull is so much more concise than the build-in find. Compare
auto& map = GetMap()
if (auto iter = map.find("key"); iter != map.end()) {
// use iter.second
}
With
if (auto value = GetMap().find_or_null("key")) {
// use *value
}
First of all std::map can contain anything. It can be a pointer (then null makes sense, but it contain a value then null has no meaning).
To overcome this you can just use a helper:
template<typename T, typename K>
auto get_optional_value(T&& map, K&& key)
{
auto it = map.find(std::forward<K>(key));
if (it == map.end()) return std::optional<typename std::decay<T>::type::mapped_type>{};
return std::optional<typename std::decay<T>::type::mapped_type>{it->second};
}
https://wandbox.org/permlink/TS56MAb97NQXkepj
Note that std::optional is quite fresh c++17.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With