end_aware_iterator.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // end_aware_iterator.hpp
  3. // iterator
  4. //
  5. // Created by Sam Jaffe on 2/7/17.
  6. //
  7. #pragma once
  8. #include <iterator/detail/traits.h>
  9. #include <iterator/facade.h>
  10. #include <iterator/iterator_fwd.hpp>
  11. namespace iterator {
  12. /**
  13. * @class end_aware_iterator
  14. * @brief An iterator that keeps track of the relative end of the range.
  15. *
  16. * @tparam It The underlying iterator type
  17. */
  18. template <typename It>
  19. class end_aware_iterator : public facade<end_aware_iterator<It>> {
  20. public:
  21. struct sentinel_type {};
  22. static constexpr sentinel_type sentinel;
  23. public:
  24. end_aware_iterator() = default;
  25. end_aware_iterator(It it, It end) : curr_(it), end_(end) {}
  26. template <typename C, typename = std::enable_if_t<detail::is_container_v<C>>>
  27. end_aware_iterator(C && container)
  28. : curr_(std::begin(container)), end_(std::end(container)) {
  29. static_assert(std::is_reference_v<C>,
  30. "Cannot access iterator of a temporary");
  31. }
  32. template <typename I>
  33. end_aware_iterator(end_aware_iterator<I> const & other)
  34. : curr_(other.curr_), end_(other.end_) {}
  35. decltype(auto) dereference() const { return *curr_; }
  36. void increment() { ++curr_; }
  37. bool at_end() const { return curr_ == end_; }
  38. bool equal_to(end_aware_iterator const & other) const {
  39. // TODO: Fix this clause
  40. return (at_end() && other.at_end()) || curr_ == other.curr_;
  41. }
  42. private:
  43. template <typename O> friend class end_aware_iterator;
  44. It curr_, end_;
  45. };
  46. template <typename C> end_aware_iterator(C &&) -> end_aware_iterator<iter<C>>;
  47. template <typename It> end_aware_iterator(It, It) -> end_aware_iterator<It>;
  48. }
  49. MAKE_ITERATOR_FACADE_TYPEDEFS_T(::iterator::end_aware_iterator);