unique_ptr_adapters.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_CONTAINERS_UNIQUE_PTR_ADAPTERS_H_
  5. #define BASE_CONTAINERS_UNIQUE_PTR_ADAPTERS_H_
  6. #include <memory>
  7. #include "base/memory/raw_ptr.h"
  8. namespace base {
  9. // This transparent comparator allows to lookup by raw pointer in
  10. // a container of unique pointers. This functionality is based on C++14
  11. // extensions to std::set/std::map interface, and can also be used
  12. // with base::flat_set/base::flat_map.
  13. //
  14. // Example usage:
  15. // Foo* foo = ...
  16. // std::set<std::unique_ptr<Foo>, base::UniquePtrComparator> set;
  17. // set.insert(std::unique_ptr<Foo>(foo));
  18. // ...
  19. // auto it = set.find(foo);
  20. // EXPECT_EQ(foo, it->get());
  21. //
  22. // You can find more information about transparent comparisons here:
  23. // http://en.cppreference.com/w/cpp/utility/functional/less_void
  24. struct UniquePtrComparator {
  25. using is_transparent = int;
  26. template <typename T, class Deleter = std::default_delete<T>>
  27. bool operator()(const std::unique_ptr<T, Deleter>& lhs,
  28. const std::unique_ptr<T, Deleter>& rhs) const {
  29. return lhs < rhs;
  30. }
  31. template <typename T, class Deleter = std::default_delete<T>>
  32. bool operator()(const T* lhs, const std::unique_ptr<T, Deleter>& rhs) const {
  33. return lhs < rhs.get();
  34. }
  35. template <typename T, class Deleter = std::default_delete<T>>
  36. bool operator()(const std::unique_ptr<T, Deleter>& lhs, const T* rhs) const {
  37. return lhs.get() < rhs;
  38. }
  39. };
  40. // UniquePtrMatcher is useful for finding an element in a container of
  41. // unique_ptrs when you have the raw pointer.
  42. //
  43. // Example usage:
  44. // std::vector<std::unique_ptr<Foo>> vector;
  45. // Foo* element = ...
  46. // auto iter = std::find_if(vector.begin(), vector.end(),
  47. // MatchesUniquePtr(element));
  48. //
  49. // Example of erasing from container:
  50. // EraseIf(v, MatchesUniquePtr(element));
  51. //
  52. template <class T, class Deleter = std::default_delete<T>>
  53. struct UniquePtrMatcher {
  54. explicit UniquePtrMatcher(T* t) : t_(t) {}
  55. bool operator()(const std::unique_ptr<T, Deleter>& o) {
  56. return o.get() == t_;
  57. }
  58. private:
  59. const raw_ptr<T> t_;
  60. };
  61. template <class T, class Deleter = std::default_delete<T>>
  62. UniquePtrMatcher<T, Deleter> MatchesUniquePtr(T* t) {
  63. return UniquePtrMatcher<T, Deleter>(t);
  64. }
  65. } // namespace base
  66. #endif // BASE_CONTAINERS_UNIQUE_PTR_ADAPTERS_H_