Phobos-Range Compatible Fixed-Dimensional Vector

88 Views Asked by At

What is the most clever way of implementing a fixed-dimensional vector in D that is compatible with the RandomAccessRange interface in Phobos? Do I have to reimplement all the members opIndex, length etc or is the cleverer way through delegation, alias this or template mixins? I've been looking at a couple of fixed-size vector structs on github D projects but none seem to care about being compatible with Phobos ranges. Update: Is just read that containers should be reference types so I guess this isn't the way to do it in D right?

1

There are 1 best solutions below

0
On BEST ANSWER

If your vector has continuous internal storage then you can just return a slice of that data from opSlice():

struct Vector
{
    private real[4] data;

    auto opSlice() { return data[]; }
}

Containers don't have to be reference types, but either way using opSlice is the usual way to get a range from a container.