openMSX
enumerate.hh
Go to the documentation of this file.
1 #ifndef ENUMERATE_HH
2 #define ENUMERATE_HH
3 
20 #include <cstddef>
21 #include <iterator>
22 #include <tuple>
23 #include <utility>
24 
25 template<typename Iterable,
26  typename Iter = decltype(std::begin(std::declval<Iterable>())),
27  typename = decltype(std::end (std::declval<Iterable>()))>
28 constexpr auto enumerate(Iterable&& iterable)
29 {
30  struct iterator {
31  size_t i;
32  Iter iter;
33 
34  constexpr bool operator==(const iterator& other) const {
35  return iter == other.iter;
36  }
37  constexpr bool operator!=(const iterator& other) const {
38  return iter != other.iter;
39  }
40 
41  constexpr bool operator==(const Iter& other) const {
42  return iter == other;
43  }
44  constexpr bool operator!=(const Iter& other) const {
45  return iter != other;
46  }
47 
48  constexpr void operator++() {
49  ++i;
50  ++iter;
51  }
52  constexpr auto operator*() const {
53  return std::tie(i, *iter);
54  }
55  };
56 
57  struct iterable_wrapper {
58  Iterable iterable;
59 
60  constexpr auto begin() {
61  return iterator{0, std::begin(iterable)};
62  }
63  constexpr auto end() {
64  return std::end(iterable);
65  }
66  };
67 
68  return iterable_wrapper{std::forward<Iterable>(iterable)};
69 }
70 
71 #endif
constexpr auto enumerate(Iterable &&iterable)
Heavily inspired by Nathan Reed's blog post: Python-Like enumerate() In C++17 http://reedbeta....
Definition: enumerate.hh:28
constexpr bool operator==(PoolIndex i, PoolIndex j)
Definition: hash_set.hh:34
constexpr bool operator!=(PoolIndex i, PoolIndex j)
Definition: hash_set.hh:35
constexpr uint128 operator*(const uint128 &a, const uint128 &b)
Definition: uint128.hh:187
constexpr auto begin(const zstring_view &x)
Definition: zstring_view.hh:82
constexpr auto end(const zstring_view &x)
Definition: zstring_view.hh:83