Bug 14625 – opIndex() doesn't work on foreach container iteration
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-05-28T03:57:00Z
Last change time
2015-08-29T09:32:48Z
Keywords
pull, rejects-valid
Assigned to
nobody
Creator
k.hara.pg
Comments
Comment #0 by k.hara.pg — 2015-05-28T03:57:02Z
A non-range container object iteration `foreach (e; c)` is
implicitly converted to a range iteration, by application of
implicit slicing like as `foreach (e; c[])`.
(Maybe the feature is not well documented in website?
http://dlang.org/statement#foreach-with-ranges
)
struct Range
{
@property bool empty() { return true; }
@property int front() { return 0; }
void popFront() {}
}
struct Container
{
Range opSlice() { return Range(); }
}
void main()
{
Container c;
foreach (e; c) {}
}
On the other hand, new integrated array operator overloading says as follows:
http://dlang.org/operatoroverloading#Slice
> To overload a[], simply define opIndex with no parameters:
But, it does not work on the container iteration. Test case is:
// Range struct is same as above
struct Container
{
Range opIndex() { return Range(); }
Range opSlice() { assert(0); }
}
void main()
{
Container c;
//foreach (e; c) {} // asserts in opSlice(), NG
foreach (e; c[]) {} // calls c.opIndex(), OK
}
The orignal post in d.learn forum:
http://forum.dlang.org/thread/[email protected]