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
25template<typename Iterable,
26 typename Iter = decltype(std::begin(std::declval<Iterable>())),
27 typename = decltype(std::end (std::declval<Iterable>()))>
28constexpr auto enumerate(Iterable&& iterable)
29{
30 struct iterator {
31 size_t i;
32 Iter iter;
33
34 [[nodiscard]] constexpr bool operator==(const iterator& other) const {
35 return iter == other.iter;
36 }
37
38 [[nodiscard]] constexpr bool operator==(const Iter& other) const {
39 return iter == other;
40 }
41
42 constexpr void operator++() {
43 ++i;
44 ++iter;
45 }
46 constexpr auto operator*() const {
47 return std::tie(i, *iter);
48 }
49 };
50
51 struct iterable_wrapper {
52 Iterable iterable;
53
54 constexpr auto begin() {
55 return iterator{0, std::begin(iterable)};
56 }
57 constexpr auto end() {
58 return std::end(iterable);
59 }
60 };
61
62 return iterable_wrapper{std::forward<Iterable>(iterable)};
63}
64
65#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 uint128 operator*(const uint128 &a, const uint128 &b)
Definition uint128.hh:191
constexpr bool operator==(const zstring_view &x, const zstring_view &y)
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)