blocks with attributes vs inlined lambda

Robert Clipsham robert at octarineparrot.com
Tue Jun 18 10:58:25 PDT 2013


On Saturday, 8 June 2013 at 14:57:17 UTC, monarch_dodra wrote:
> My beef though is that the syntax is a bit opaque, and not 
> really idiomatic. It looks more like a hacker's trick than a 
> real language feature. It's not something you'd do "naturally". 
> At least, I know a beginner may not feal comfortable with this.
>
> Given that users are now actually doing this, that we have 
> proof it works and is a useful feature, shouldn't we push to 
> have actual blocks with attributes in the language?
>
> I think we should... Thoughts?

Here's my go at cleaning up the syntax a bit:
----
auto block(string attr)() {
     static struct Blk {
         mixin(q{
             void opBinary(string op:"in", T)(T dg) } ~ attr ~ q{
                 if (is(typeof(() } ~ attr ~ q{ { dg(); }))) {
                 dg();
             }
             void opBinary(string op:"in", T)(T dg) if 
(!is(typeof(() } ~ attr ~ ` { dg(); }))) {
                 static assert(false, "Provided delegate is not " 
~ "` ~ attr ~ `");
             }
         `);
     }
     return Blk();
}

void main() {
     // Works
     block!"nothrow" in {
         // Doesn't throw
     };

     // Fails
     block!"nothrow" in {
         throw new Exception("");
     };
}
----
Downsides are the required semicolon (needed for your method too) 
and abuse of operator overloading.


More information about the Digitalmars-d mailing list