Forcing closures to come on the stack

Simen Kjaeraas simen.kjaras at gmail.com
Mon Aug 8 14:20:38 PDT 2011


On Mon, 08 Aug 2011 04:51:19 +0200, Mehrdad <wfunction at hotmail.com> wrote:

> I just made something I thought I'd share.
>
> It's great for those times when the compiler decides to randomly put a  
> closure on the heap.
>
> The usage is pretty simple:
>
>      int x = 5;
>      auto adder5 = mixin(closure!x(q{(int a) { return a + x; }}));
>      assert(adder5(10) == 15);
>
> It returns a callable struct whose body is the given string; the  
> template parameters are the variables under closure (in this case, x).
>
> The generated code looks like (minus a little beautification on my part):
>
>      (delegate(ref int x) {
>          static struct State {
>              int* px;
>              @property ref int x() { return *this.px; }
>              auto opCall(int a) { return a + x; }
>          }
>          State tmp;
>          tmp.px = &x;
>          return tmp;
>      })(x)
>
> So when you assign it to something, that something becomes a struct with  
> opCall overloaded. You can then take the address of opCall on the  
> struct, and you get a delegate.
>
> Thoughts?

You could use the 'scope' keyword, no?

Upon perusal of the documentation, it seems this is nowhere mentioned, and
a report may be in order.

-- 
   Simen


More information about the Digitalmars-d mailing list