ForwardRange and BidirectionalRange

You will learn the use of ForwardRange and BidirectionalRange in this lesson.

We'll cover the following

ForwardRange

InputRange models a range where elements are taken out of the range as they are iterated over.

Some ranges are capable of saving their states, as well as operating as an InputRange. For example, FibonacciSeries objects can save their states because these objects can freely be copied, and the two copies continue their lives independently from each other.

ForwardRange provides the save member function, which is expected to return a copy of the range. The copy that save returns must operate independently from the range object that it was copied from; iterating over one copy must not affect the other copy.

Importing std.array automatically makes slices become ForwardRange ranges.

In order to implement save for FibonacciSeries, we can simply return a copy of the object:

struct FibonacciSeries { 
// ...
    FibonacciSeries save() const {
        return this;
    }
}

The returned copy is a separate range that would continue from the point where it was copied from.

We can demonstrate that the copied object is independent of the actual range with the following program. In the following code, the algorithm std.range.popFrontN() removes a specified number of elements from the specified range:

Get hands-on with 1400+ tech skills courses.