lambdas and function literals in classes

Artur Skawina art.08.09 at gmail.com
Tue Jul 9 05:32:43 PDT 2013


On 07/09/13 12:50, John Colvin wrote:
> JS asked about this in the main group, but here is more appropriate and I'm quite interested myself.

Function/delegate *literals* in aggregates are not accepted by the compiler.
It's just a compiler issue; iirc the frontend recently got a bit smarter about
figuring out what is/isn't a delegate, so maybe at some point the restriction
will be gone. Right now, everybody runs into this, and has to work around by
inventing dummy names for the literals. Ie

   struct S {
      enum a = { return 42; }();
   }

does not work.You have to use

   struct S {
      static ugh() { return 42; };
      enum a = ugh();
   }

which of course litters the namespace and obfuscates what's happening.

The 

   enum a = { return 42; }();

line will work outside of the struct/class/whatever.


For this to work the compiler would have figure out that the function
literal really is just a function literal, ie does not access any field
of the struct and does not need any context pointer. Which is possible,
but does not currently happen. It's also not possible to /explicitly/
specify - there's no way to mark *just* the literal as "static". 

   struct S {
      static enum a = { return 42; }();
   }

Works - but that's not enough:

   struct S {
      static mixin({ return "int a;"; }()); // oops, 'a' is static.
   }


IIRC this issue is already reported somewhere in bugzilla. 

artur


More information about the Digitalmars-d-learn mailing list