MyGenerator represents a (possibly) finite sequence of integers, that is expensive to compute. So I don't want to generate them all upfront and put them into a container.
struct MyGenerator{
bool HasNext();
int Next();
}
To print them all:
MyGenerator generator;
while (generator.HasNext()) {
std::cout << generator.Next() << std::endl;
}
How to implement a similar generator that follows the protocol of a forward_iterator?
boost::function_input_iterator comes close, but I do not know the number of elements upfront.
First off, look at the implementation of
boost::function_input_iterator
, since what you want is the same except that testing the equality of iterators must be modified to cope with the fact you don't know whether it's infinite and if not how many items there are. Once you get used to the style, the authors of Boost will give you better advice via their code than I will :-)That said, something along these lines (untested):
size_t
, since 64 bits will never wrap in practice. To be safe you could use a different type to keep count:uint64_t
or if all else falls a user-defined large integer type. Consult thestd::iterator
documentation though, because once your iterator runs longer thansize_t
you want to give it a non-defaultdifference_type
.Generator
must be copyable (and the copy must have equal state with the original, and the two must thereafter advance independently) or else you have no chance of implementing aforward_iterator
other than by storing a potentially unbounded amount of output from the generator. If you only need aninput_iterator
then you could refer to theGenerator
by reference.MyGenerator
, rather you just want to know how to write a possibly-infinite iterator, then you can get rid of the template parameter, store whatever state you like in the iterator, and just put the code to advance the state inadvance()
.