opSlice() magic for foreach now works?

Steven Schveighoffer schveiguy at yahoo.com
Wed Mar 30 07:29:52 PDT 2011


On Wed, 30 Mar 2011 10:06:26 -0400, spir <denis.spir at gmail.com> wrote:

> Hello,
>
> I was trying std.container's SList and noticed foreach iteration works  
> for it, while it defines neither opApply, nore a (complete) input range  
> interface. But it does implement a parameter-less opSlice, which maps to  
> "l2 = l1[];". More precisely, SList (as other container types) defines a  
> 'Range' struct type which is the return type of opSlice().
> TDPL states this method should automagically deal as standard traversal  
> for foreach (when no opApply or range interface is defined on the  
> collection to be traverseditself, I guess). But the magic did not work  
> up to very recently.

Apparently, it works for SList all the way back to at least 2.050, but I'm  
not sure why.  It doesn't work for a basic case in 2.052:

struct S
{
     struct R
     {
         @property int front() { return 0;}
         void popFront() {}
         @property bool empty() const { return true;}
     }

     R opSlice() { return R();}
}


void main()
{
     S s;
     foreach(int n; s) {}
}


testopslice.d(19): Error: no property 'opApply' for type 'S'
testopslice.d(19): Error: opApply() function for S must return an int

-Steve


More information about the Digitalmars-d mailing list