adapters.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2014 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_ADAPTERS_H_
  5. #define BASE_CONTAINERS_ADAPTERS_H_
  6. #include <stddef.h>
  7. #include <iterator>
  8. #include <utility>
  9. namespace base {
  10. namespace internal {
  11. // Internal adapter class for implementing base::Reversed.
  12. template <typename T>
  13. class ReversedAdapter {
  14. public:
  15. using Iterator = decltype(std::rbegin(std::declval<T&>()));
  16. explicit ReversedAdapter(T& t) : t_(t) {}
  17. ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}
  18. ReversedAdapter& operator=(const ReversedAdapter&) = delete;
  19. Iterator begin() const { return std::rbegin(t_); }
  20. Iterator end() const { return std::rend(t_); }
  21. private:
  22. T& t_;
  23. };
  24. } // namespace internal
  25. // Reversed returns a container adapter usable in a range-based "for" statement
  26. // for iterating a reversible container in reverse order.
  27. //
  28. // Example:
  29. //
  30. // std::vector<int> v = ...;
  31. // for (int i : base::Reversed(v)) {
  32. // // iterates through v from back to front
  33. // }
  34. template <typename T>
  35. internal::ReversedAdapter<T> Reversed(T& t) {
  36. return internal::ReversedAdapter<T>(t);
  37. }
  38. } // namespace base
  39. #endif // BASE_CONTAINERS_ADAPTERS_H_