nested functions and closures
Johannes Pfau
nospam at example.com
Mon Feb 11 10:59:36 PST 2013
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?
More information about the Digitalmars-d
mailing list