iterator_range.h 2.4 KB

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