question about foreach, opApply, and delegates
BCS
none at anon.com
Mon Jun 8 22:16:43 PDT 2009
Hello grauzone,
> Jerry Quinn wrote:
>
>> Hi, all. I find myself a little confused about how foreach, opApply,
>> and delegates interact according to the docs.
>>
>> Foreach on an aggregate will use the opApply call (assuming ranges
>> aren't being used). So if we use a simple example below, what
>> exactly is the delegate that is passed to opApply? The docs say a
>> delegate is a pairing of an object reference and a function, where
>> the object is passed as the 'this' parameter to the function. But
>> that doesn't seem to be the case here.
>>
>> Is a virtual object with a function encompassing the body of the
>> foreach being silently created and passed in?
>>
In one way of looking at it every stack frame is a virtual struct <g> so
yes, sort of.
> The foreach body is like a nested function. Your example is (probably,
> maybe this is wrong/oversimplified) compiled to something like this:
>
> void foo() {
> C c = new C;
> int bla;
> void something(uint v) {
> bla = 123;
> writefln(v);
> }
> c.opApply(&something);
> }
IIRC if you compile with the -v flag you can even see DMD running code generation
for the foreach bodies.
> (Although I think
> it's perfectly fine to post this here, because the "gurus" don't post
> and probably don't even read d.D.learn.)
I may not count as a "guru" but I'm "not a beginner" and do read it.
More information about the Digitalmars-d
mailing list