unique_ptr_adapters.h 2.4 KB

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