struct Foo { uint front() { return 1; } int opApply(int delegate(ref uint) dg) { return 1; } } void main() { Foo foo; foreach(elem; foo) {} } test8.d(68): Error: no property 'empty' for type 'Foo' test8.d(68): Error: no property 'popFront' for type 'Foo' Clearly, DMD saw that front() was present and tried to use range foreach. This is incorrect because: 1. Only part of the range interface existed. The opApply interface was complete and should have worked. 2. If someone defines both a range interface and an opApply interface with the same types, they probably have a good reason, since ranges serve other purposes, but opApply exists **only** for foreach. 3. Some things, like iterating over trees, can be done more efficiently with control of the stack than without. Also, once opSlice becomes able to define implicit conversions to ranges for foreach loops, any opApply's defined should take precedence over this for the reasons mentioned above.
Forgot to mention: Also, when using virtual functions, it may sometimes be reasonable to define an opApply as an optimization for foreach loops, even if the range-based foreach has the exact same semantics. For example: class Foo { SomeType front() { return _front;} void popFront() { // do stuff. } bool empty() { return _empty; } } In this case each iteration will require three virtual function calls, whereas if opApply were used, the overhead would be reduced to a single delegate call.
Doing this will also fix bug 2984 (which is marked as a regression, but isn't really).
*** This issue has been marked as a duplicate of issue 2984 ***
This bug supersedes bug 2984, because solving this bug will not only address the problem in 2984, but address a very important problem that is not identified in 2984. That is: if opApply is present *at all* it should override any range functionality when sending to foreach. This includes the case not identified in 2984 in which valid range operations are present *alongside* opApply. e.g.: import std.stdio; struct S { int front() { return 0; } bool empty() { return true; } void popFront() { } int opApply(int delegate(ref int x) dg) { writeln("inside opapply"); int x = 0; return dg(x); } } void main() { S s; foreach(i; s) { writeln("inside loop %d", i); } } Currently outputs nothing, it should output: inside opapply inside loop 0
Then bug 2984 should be marked as a duplicate for this bug, right? There is definitely duplication in this 2 bugs, and there is no point to keep both open. I won't do it just in case I'm messing it up again ;)
Yeah, probably :) I'll do it.
*** Issue 2984 has been marked as a duplicate of this issue. ***
http://www.dsource.org/projects/dmd/changeset/295
More discussion: http://www.digitalmars.com/d/archives/digitalmars/D/opApply_Vs._Ranges_What_should_take_precedence_101124.html
Fixed dmd 2.038