iterator_range.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //===- iterator_range.h - A range adaptor for iterators ---------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This provides a very simple, boring adaptor for a begin and end iterator
  10. /// into a range type. This should be used to build range views that work well
  11. /// with range based for loops and range based constructors.
  12. ///
  13. /// Note that code here follows more standards-based coding conventions as it
  14. /// is mirroring proposed interfaces for standardization.
  15. ///
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ADT_ITERATOR_RANGE_H
  18. #define LLVM_ADT_ITERATOR_RANGE_H
  19. #include <utility>
  20. namespace llvm {
  21. /// A range adaptor for a pair of iterators.
  22. ///
  23. /// This just wraps two iterators into a range-compatible interface. Nothing
  24. /// fancy at all.
  25. template <typename IteratorT>
  26. class iterator_range {
  27. IteratorT begin_iterator, end_iterator;
  28. public:
  29. //TODO: Add SFINAE to test that the Container's iterators match the range's
  30. // iterators.
  31. template <typename Container>
  32. iterator_range(Container &&c)
  33. //TODO: Consider ADL/non-member begin/end calls.
  34. : begin_iterator(c.begin()), end_iterator(c.end()) {}
  35. iterator_range(IteratorT begin_iterator, IteratorT end_iterator)
  36. : begin_iterator(std::move(begin_iterator)),
  37. end_iterator(std::move(end_iterator)) {}
  38. IteratorT begin() const { return begin_iterator; }
  39. IteratorT end() const { return end_iterator; }
  40. bool empty() const { return begin_iterator == end_iterator; }
  41. };
  42. /// Convenience function for iterating over sub-ranges.
  43. ///
  44. /// This provides a bit of syntactic sugar to make using sub-ranges
  45. /// in for loops a bit easier. Analogous to std::make_pair().
  46. template <class T> iterator_range<T> make_range(T x, T y) {
  47. return iterator_range<T>(std::move(x), std::move(y));
  48. }
  49. template <typename T> iterator_range<T> make_range(std::pair<T, T> p) {
  50. return iterator_range<T>(std::move(p.first), std::move(p.second));
  51. }
  52. }
  53. #endif