mapfindptr.h 1.5 KB

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