nested functions and closures

Zach the Mystic reachBUTMINUSTHISzach at gOOGLYmail.com
Mon Feb 11 12:41:26 PST 2013


On Monday, 11 February 2013 at 18:59:37 UTC, Johannes Pfau wrote:
> When debugging gdc I've found some at least for me interesting
> behavior which I'm trying to understand now:
>
> ----
> auto testFunction() {
>     int a = 41;
>     int nestedFunc() { return ++a; }
>
>     struct NestedStruct {
>         int answer() { return nestedFunc(); }
>     }
>
>     return NestedStruct();
> }
>
> writeln(testFunction().answer());
> ----
>
> This is valid D code, creates a closure.
>
> ----
> class testClass
> {
>     int a = 41;
>     int nestedFunc() { return ++a; }
>
>     struct NestedStruct {
>         int answer() { return nestedFunc(); }
>     }
> 
>     auto getStruct() { return NestedStruct(); }
> }
>
> writeln((new TestClass()).getStruct().answer);
> ----
>
> This does not compile:
> test.d(33): Error: this for nestedFunc needs to be type 
> testClass not
> type NestedStruct
>
> Is this intended? It seems to be very similar to the function 
> closure
> code. Couldn't NestedStruct just get a pointer to the testClass 
> to
> access its variables? Or am I missing something?
>
> Everything works fine if NestedStruct is a class and not a 
> struct so I
> guess this functionality was disabled deliberately. But why? 
> And why
> wasn't using a nested struct in functions in a similar way 
> disallowed as
> well?

I recently wrote an article partly on this topic which may be of 
interest to you. Apologies if it is not. See part one: neutrons.

http://forum.dlang.org/thread/ririagrqecshjljcdubd@forum.dlang.org


More information about the Digitalmars-d mailing list