openMSX
KeyRange.hh
Go to the documentation of this file.
1 #ifndef KEYRANGE_HH
2 #define KEYRANGE_HH
3 
4 #include <iterator>
5 #include <tuple>
6 
7 namespace detail {
8 
9 template<typename MAP, size_t N> class KeyIterator
10 {
11  using map_iter = typename MAP::const_iterator;
12  using pair_type = typename std::iterator_traits<map_iter>::value_type;
13 public:
14 
15  using value_type = const std::tuple_element_t<N, pair_type>;
16  using pointer = value_type*;
18  using difference_type = typename std::iterator_traits<map_iter>::difference_type;
19  using iterator_category = std::forward_iterator_tag;
20 
21  /*implicit*/ KeyIterator(map_iter it_) : it(it_) {}
22  reference operator*() const { return std::get<N>(*it); }
23  KeyIterator& operator++() { ++it; return *this; }
24  bool operator==(const KeyIterator& other) const { return it == other.it; }
25  bool operator!=(const KeyIterator& other) const { return it != other.it; }
26 private:
27  map_iter it;
28 };
29 
30 template<typename MAP, size_t N> class KeyRange
31 {
32 public:
33  explicit KeyRange(const MAP& map_)
34  : map(map_) {}
35 
36  KeyIterator<MAP, N> begin() const { return map.begin(); }
37  KeyIterator<MAP, N> end() const { return map.end(); }
38 private:
39  const MAP& map;
40 };
41 
42 } // namespace detail
43 
44 
45 // Input: a collection that contains key-value pairs or tuples.
46 // Output: a range that represents (only) the keys, the values or the N-th
47 // elements of the items in the input.
48 
49 template<typename MAP> detail::KeyRange<MAP, 0> keys(const MAP& map)
50 {
51  return detail::KeyRange<MAP, 0>(map);
52 }
53 
54 template<typename MAP> detail::KeyRange<MAP, 1> values(const MAP& map)
55 {
56  return detail::KeyRange<MAP, 1>(map);
57 }
58 
59 template<size_t N, typename MAP> detail::KeyRange<MAP, N> elements(const MAP& map)
60 {
61  return detail::KeyRange<MAP, N>(map);
62 }
63 
64 #endif
detail::KeyRange< MAP, 1 > values(const MAP &map)
Definition: KeyRange.hh:54
const std::tuple_element_t< N, pair_type > value_type
Definition: KeyRange.hh:15
KeyIterator(map_iter it_)
Definition: KeyRange.hh:21
KeyRange(const MAP &map_)
Definition: KeyRange.hh:33
std::forward_iterator_tag iterator_category
Definition: KeyRange.hh:19
detail::KeyRange< MAP, N > elements(const MAP &map)
Definition: KeyRange.hh:59
KeyIterator< MAP, N > begin() const
Definition: KeyRange.hh:36
KeyIterator< MAP, N > end() const
Definition: KeyRange.hh:37
typename std::iterator_traits< map_iter >::difference_type difference_type
Definition: KeyRange.hh:18
reference operator*() const
Definition: KeyRange.hh:22
bool operator!=(const KeyIterator &other) const
Definition: KeyRange.hh:25
bool operator==(const KeyIterator &other) const
Definition: KeyRange.hh:24
value_type & reference
Definition: KeyRange.hh:17
detail::KeyRange< MAP, 0 > keys(const MAP &map)
Definition: KeyRange.hh:49
KeyIterator & operator++()
Definition: KeyRange.hh:23
value_type * pointer
Definition: KeyRange.hh:16