range algorithms on container class

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 9 10:23:51 UTC 2020


On Wednesday, January 8, 2020 10:28:23 PM MST Alex Burton via Digitalmars-d-
learn 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 ?

You could make a container a range, but then iterating over it would pop
elements off of the container, which almost certainly isn't something that
you want. Containers are normally supposed to overload opSlice which returns
a range over the container so that you can iterate over the container
without altering it. And if you use a container with foreach, the compiler
will actually insert the opSlice call for you. Alternatively, you can define
opApply on the container. Outside of foreach though, you'd have to
explicitly slice the container.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list