| 44 | using underlying_iterator_variant = std::variant<typename Maps::iterator...>; |
| 45 | |
| 46 | class iterator { |
| 47 | public: |
| 48 | using value_type = VariantMap::value_type; |
| 49 | using difference_type = std::ptrdiff_t; |
| 50 | using pointer = value_type*; |
| 51 | using reference = value_type; |
| 52 | using iterator_category = std::forward_iterator_tag; |
| 53 | |
| 54 | underlying_iterator_variant it_var; |
| 55 | |
| 56 | // mutable cache to support operator-> (so that it->second works) |
| 57 | mutable std::unique_ptr<value_type> cached_value_ptr_; |
| 58 | |
| 59 | iterator() = default; |
| 60 | |
| 61 | explicit iterator(underlying_iterator_variant v) |
| 62 | : it_var(std::move(v)) {} |
| 63 | |
| 64 | iterator(const iterator& other) |
| 65 | : it_var(other.it_var), cached_value_ptr_(nullptr) {} |
| 66 | |
| 67 | iterator& operator=(const iterator& other) { |
| 68 | if (this != &other) { |
| 69 | it_var = other.it_var; |
| 70 | cached_value_ptr_.reset(); // clear the cache |
| 71 | } |
| 72 | return *this; |
| 73 | } |
| 74 | |
| 75 | value_type operator*() const { |
| 76 | return std::visit([](auto& it) -> value_type { return *it; }, it_var); |
| 77 | } |
| 78 | |
| 79 | value_type* operator->() const { |
| 80 | // @todo we need to make a copy here (stored in unique_ptr) because the |
| 81 | // value_type appears to be pair<const K, V> instead of <K, V> or something |
| 82 | // related... |
| 83 | cached_value_ptr_ = std::make_unique<value_type>(**this); |
| 84 | return cached_value_ptr_.get(); |
| 85 | } |
| 86 | |
| 87 | iterator& operator++() { |
| 88 | std::visit([](auto& it) { ++it; }, it_var); |
| 89 | return *this; |
| 90 | } |
| 91 | |
| 92 | iterator operator++(int) { |
| 93 | iterator tmp(*this); |
| 94 | ++(*this); |
| 95 | return tmp; |
| 96 | } |
| 97 | |
| 98 | bool operator==(const iterator& other) const { |
| 99 | return it_var == other.it_var; |
| 100 | } |
| 101 | |
| 102 | bool operator!=(const iterator& other) const { |
| 103 | return !(*this == other); |