digitalmars.D.learn - Compiler doesn't see the inherited opApply in this example
- Mike L. (39/39) Jul 03 2009 Hello, can anybody explain why the following code compiles with -version...
- Mike L. (1/1) Jul 03 2009 Apparently I'm missing some basic concept about how D does OO since I r...
- Steven Schveighoffer (5/42) Jul 07 2009 /* add this line (see
Hello, can anybody explain why the following code compiles with -version=works but not without? module test; import std.stdio; abstract class Parent { int opApply(int delegate(ref int) dg) { int fakeDelegate(ref uint fake, ref int content) { return dg(content); } return opApply(&fakeDelegate); } abstract int opApply(int delegate(ref uint, ref int) dg); } class Child : Parent { override int opApply(int delegate(ref uint, ref int) dg) { uint index = 0; for(int content = 1; content < 6; content++) { int result = dg(index, content); if(result != 0) return result; index++; } return 0; } } void main() { version(works) Parent child = new Child(); else Child child = new Child(); foreach(int content; child) writefln(content); } I'm making some collection classes and had the same problem. It seems like for some reason the compiler can't match the index-free foreach() in the child, but can in the parent. It obviously knows it's there, or else it wouldn't compile because the index-free opApply would be abstract. Any thoughts?
Jul 03 2009
Apparently I'm missing some basic concept about how D does OO since I recreated the problem with a simpler function. I'll re-examine things...
Jul 03 2009
On Fri, 03 Jul 2009 17:42:45 -0400, Mike L. <sgtmuffles myrealbox.com> wrote:module test; import std.stdio; abstract class Parent { int opApply(int delegate(ref int) dg) { int fakeDelegate(ref uint fake, ref int content) { return dg(content); } return opApply(&fakeDelegate); } abstract int opApply(int delegate(ref uint, ref int) dg); } class Child : Parent {/* add this line (see http://www.digitalmars.com/d/2.0/function.html#function-inheritance) */ alias Parent.opApply opApply;override int opApply(int delegate(ref uint, ref int) dg) { uint index = 0; for(int content = 1; content < 6; content++) { int result = dg(index, content); if(result != 0) return result; index++; } return 0; } } void main() { version(works) Parent child = new Child(); else Child child = new Child(); foreach(int content; child) writefln(content); }
Jul 07 2009