range algorithms on container class

rikki cattermole rikki at cattermole.co.nz
Thu Jan 9 05:56:20 UTC 2020


On 09/01/2020 6:28 PM, Alex Burton wrote:
> I am writing a specialised container class, and want to make it work 
> like a normal array with range functions.
> After some struggle, I look at the code for std.container.array and see 
> this comment :
> 
> When using `Array` with range-based functions like those in 
> `std.algorithm`,
>   * `Array` must be sliced to get a range (for example, use `array[].map!`
>   * instead of `array.map!`). The container itself is not a range.
> 
> 
> I had thought the compiler would make a generic random access range that 
> works with the built in array for anything else with a simililar 
> interface, but it doesn't.
> 
> Does that mean it is not possible to have a library container 
> implementation that works nicely with range algorithms ? Do you have to 
> slice it like the comment suggests ?

Slicing via the opSlice operator overload is a convention, not a 
requirement.

The reason this is necessary is because you do not want to be calling 
input range methods directly on a container. If you do this, the 
container itself will have the state of the input range, with no way to 
reset it to the full contents.

The trick is to store this into a Voldemort type returned by the opSlice 
operator overload.

If you want it to behave like an actual array and not the Array 
container in Phobos, you will have to use a lot more operator overloads 
(which you should be doing for a list). These will be on the container 
itself. One of these is opApply which allows for iterating over it.


More information about the Digitalmars-d-learn mailing list