Polymorphic ranges?

Dmitry Olshansky dmitry.olsh at gmail.com
Sun May 1 02:50:12 PDT 2011


On 01.05.2011 6:33, Andrej Mitrovic wrote:
> As an example I have a cyclic buffer (using std.range.Cycle) where I can set the lower and upper bounds of the buffer. I'd also like to enable a stepping mode, so I thought first about using std.range.Stride.
>
> The code: http://codepad.org/TR7NDWTC
>
> This line is commented out:
> //~ buffer = stride(buffer, newStep);
>
> Obviously I can't assign a Stride structure to a Cycle structure. Structures aren't polymorphic.
>
> The idea was that the private _buffer could be traversed in different ways, and the Work structure would allow reconfiguration on how the public "buffer" walks through the private _buffer array, this would be done at runtime via function calls like "setStep" which changes the buffer type.
>
> But this isn't possible since buffer can only be one type, since it's a structure.
>
> So the question is, how can I use std.range and its various types  polymorphically, is that in any way possible?
>
>  From what I can tell std.range functions all return structs. I was hoping of being able to do something like:
>
> class Work
> {
>      float[256] _buffer;
>      InfiniteRange buffer;
>
>      this() { buffer = new InfiniteRange(_buffer); }  // initialize
>
>      void setStride()
>      {
>          buffer = new Stride(buffer);  // now buffer has a dynamic type of Stride, which would be a subtype of InfiniteRange
>      }
> }
>
> And then main would create a Work object, and call its buffer.front and buffer.popFront properties, and later call setStride to change how the object behaves by simply creating a new subtype which has the same interface but different behavior.
>
> But I can't do that here since pretty much everything in std.range returns a struct.
There is a polymorphic wrapper for any range in std.range, try 
inputRangeObject & outputRangeObject. Every such range object is derived 
from the most suitable interface InputRange, ForwardRange etc.

-- 
Dmitry Olshansky



More information about the Digitalmars-d-learn mailing list