diff options
author | Devtools Arcadia <arcadia-devtools@yandex-team.ru> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /util/generic/mapfindptr.h | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'util/generic/mapfindptr.h')
-rw-r--r-- | util/generic/mapfindptr.h | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/util/generic/mapfindptr.h b/util/generic/mapfindptr.h new file mode 100644 index 0000000000..bc10cac60f --- /dev/null +++ b/util/generic/mapfindptr.h @@ -0,0 +1,60 @@ +#pragma once + +#include <type_traits> + +/** MapFindPtr usage: + +if (T* value = MapFindPtr(myMap, someKey) { + Cout << *value; +} + +*/ + +template <class Map, class K> +inline auto MapFindPtr(Map& map, const K& key) { + auto i = map.find(key); + + return (i == map.end() ? nullptr : &i->second); +} + +template <class Map, class K> +inline auto MapFindPtr(const Map& map, const K& key) { + auto i = map.find(key); + + return (i == map.end() ? nullptr : &i->second); +} + +/** helper for THashMap/TMap */ +template <class Derived> +struct TMapOps { + template <class K> + inline auto FindPtr(const K& key) { + return MapFindPtr(static_cast<Derived&>(*this), key); + } + + template <class K> + inline auto FindPtr(const K& key) const { + return MapFindPtr(static_cast<const Derived&>(*this), key); + } + + template <class K, class DefaultValue> + inline auto Value(const K& key, const DefaultValue& defaultValue) const -> std::remove_reference_t<decltype(*this->FindPtr(key))> { + if (auto found = FindPtr(key)) { + return *found; + } + return defaultValue; + } + + template <class K, class V> + inline const V& ValueRef(const K& key, V& defaultValue) const { + static_assert(std::is_same<std::remove_const_t<V>, typename Derived::mapped_type>::value, "Passed default value must have the same type as the underlying map's mapped_type."); + + if (auto found = FindPtr(key)) { + return *found; + } + return defaultValue; + } + + template <class K, class V> + inline const V& ValueRef(const K& key, V&& defaultValue) const = delete; +}; |