GeneratorIter.h
Go to the documentation of this file.
1 #ifndef WIRECELL_GENERATORITER
2 #define WIRECELL_GENERATORITER
3 
4 #include <boost/iterator/iterator_categories.hpp>
5 #include <boost/iterator/iterator_facade.hpp>
6 
7 namespace WireCell {
8 
9  // template <typename Callable, typename Value>
10  // struct NullGenerator : public Callable {
11  // NullGenerator() {}
12  // ~NullGenerator() {}
13  // Value operator()() { return 0; }
14  // operator bool() const { return false;}
15  // bool operator==(const NullGenerator& rhs) const { return true; }
16  // bool operator==(const Callable& rhs) const { return true; }
17  // };
18 
19  /** A generator iterator using a Callable.
20  *
21  * Requirements on Callable
22  * - returns Value.
23  * - evaluates as false when it is not exhausted, true otherwise.
24  * - copy-by-value, copies are independent.
25  * - instances must be testable for equality.
26  *
27  * Inspired by:
28  * http://stackoverflow.com/questions/27604201/implement-lazy-generator-as-forward-iterator-in-c
29  */
30  template <typename Callable, typename Value>
31  struct GeneratorIter : public boost::iterator_facade<
32  GeneratorIter<Callable, Value>,
33  Value,
34  boost::forward_traversal_tag
35  >
36  {
37  GeneratorIter(const Callable& func)
38  : count(0), func(func), last_val(0)
39  {
40  advance();
41  }
42  void advance() {
43  if (func) {
44  last_val = func();
45  }
46  }
47  Value operator*() const {
48  return last_val;
49  }
51  advance();
52  return *this;
53  }
55  GeneratorIter res = *this;
56  advance();
57  return res;
58  }
59  bool operator==(const GeneratorIter& rhs) const {
60  return (!func && !rhs.func) || (func == rhs.func && count == rhs.count);
61  }
62  bool operator!=(const GeneratorIter& rhs) const {
63  return !(*this == rhs);
64  }
65 
66  operator bool() const {
67  return func;
68  }
69 
70  size_t count;
71  Callable func;
73  };
74 
75 
76 }
77 
78 #endif
GeneratorIter & operator++()
Definition: GeneratorIter.h:50
GeneratorIter operator++(int)
Definition: GeneratorIter.h:54
Value operator*() const
Definition: GeneratorIter.h:47
Definition: Main.h:22
bool operator==(const GeneratorIter &rhs) const
Definition: GeneratorIter.h:59
GeneratorIter(const Callable &func)
Definition: GeneratorIter.h:37
bool operator!=(const GeneratorIter &rhs) const
Definition: GeneratorIter.h:62
int bool
Definition: qglobal.h:345