mapfindptr.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #pragma once
  2. #include <util/system/compiler.h>
  3. #include <type_traits>
  4. #include <utility>
  5. /** MapFindPtr usage:
  6. if (T* value = MapFindPtr(myMap, someKey) {
  7. Cout << *value;
  8. }
  9. */
  10. template <class Map, class K>
  11. inline auto MapFindPtr(Map& map Y_LIFETIME_BOUND, const K& key) {
  12. auto i = map.find(key);
  13. return (i == map.end() ? nullptr : &i->second);
  14. }
  15. template <class Map, class K>
  16. inline auto MapFindPtr(const Map& map Y_LIFETIME_BOUND, const K& key) {
  17. auto i = map.find(key);
  18. return (i == map.end() ? nullptr : &i->second);
  19. }
  20. /** helper for THashMap/TMap */
  21. template <class Derived>
  22. struct TMapOps {
  23. template <class K>
  24. inline auto FindPtr(const K& key) Y_LIFETIME_BOUND {
  25. return MapFindPtr(static_cast<Derived&>(*this), key);
  26. }
  27. template <class K>
  28. inline auto FindPtr(const K& key) const Y_LIFETIME_BOUND {
  29. return MapFindPtr(static_cast<const Derived&>(*this), key);
  30. }
  31. template <class K, class DefaultValue>
  32. inline auto Value(const K& key, DefaultValue&& defaultValue) const {
  33. auto found = FindPtr(key);
  34. return found ? *found : std::forward<DefaultValue>(defaultValue);
  35. }
  36. template <class K, class V>
  37. inline const V& ValueRef(const K& key, V& defaultValue Y_LIFETIME_BOUND) const Y_LIFETIME_BOUND {
  38. 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.");
  39. if (auto found = FindPtr(key)) {
  40. return *found;
  41. }
  42. return defaultValue;
  43. }
  44. template <class K, class V>
  45. inline const V& ValueRef(const K& key, V&& defaultValue Y_LIFETIME_BOUND) const Y_LIFETIME_BOUND = delete;
  46. };