recursive_iterator_base.hpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #pragma once
  2. #include "../end_aware_iterator.hpp"
  3. #include "recursive_iterator_traits.hpp"
  4. namespace iterator { namespace detail {
  5. template <typename Iterator, typename = void> class recursive_iterator_base;
  6. /**
  7. * @class recursive_iterator_base
  8. * @brief A thin wrapper around end_aware_iterator for the purposes of
  9. * template metaprogramming.
  10. */
  11. template <typename Iterator, typename>
  12. class recursive_iterator_base : public end_aware_iterator<Iterator> {
  13. public:
  14. using super = end_aware_iterator<Iterator>;
  15. protected:
  16. using recursive_category = terminal_layer_tag_t;
  17. public:
  18. using super::super;
  19. recursive_iterator_base(super const & iter) : super(iter) {}
  20. recursive_iterator_base(super && iter) : super(std::move(iter)) {}
  21. recursive_iterator_base() = default;
  22. protected:
  23. decltype(auto) get() const { return super::operator*(); }
  24. };
  25. /**
  26. * @class recursive_iterator_base
  27. * @brief An SFINAE specialization of recursive_iterator_base for associative
  28. * containers
  29. *
  30. * Because it is possible for recursive iterator to step over multiple layers
  31. * of associative containers, the return type is made into a tuple, so that
  32. * the caller does not need to write something like
  33. * `it->second.second.second'. Instead, the return type is a tuple of
  34. * references, so that the caller can write code like `std::get<3>(*it)'.
  35. *
  36. * For example, the ref type for std::map<int, std::map<float, double> >
  37. * with this would be std::tuple<int const&, float const&, double &>.
  38. */
  39. template <typename Iterator>
  40. class recursive_iterator_base<Iterator, is_associative_t<Iterator>>
  41. : public end_aware_iterator<Iterator> {
  42. public:
  43. using super = end_aware_iterator<Iterator>;
  44. using first_type = decltype((std::declval<Iterator>()->first));
  45. using second_type = decltype((std::declval<Iterator>()->second));
  46. protected:
  47. using recursive_category = continue_layer_tag_t;
  48. public:
  49. using super::super;
  50. recursive_iterator_base(super const & iter) : super(iter) {}
  51. recursive_iterator_base(super && iter) : super(std::move(iter)) {}
  52. recursive_iterator_base() = default;
  53. protected:
  54. /**
  55. * An alternative function to operator*(), which allows single layer
  56. * recursive iterators (on associative containers) to return the
  57. * underlying value/reference type, and nested containers to propogate
  58. * a tuple or a pair as necessary.
  59. */
  60. std::tuple<first_type &, second_type &> get() const {
  61. auto & pair = super::operator*();
  62. return std::tie(pair.first, pair.second);
  63. }
  64. };
  65. }}