Variables with scoped destruction in closures

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 14 10:26:48 PDT 2016


On Friday, 14 October 2016 at 14:00:53 UTC, ag0aep6g wrote:
> As for ways to make this work:
>
> 1) You can move s to the heap yourself:
[...]
> 2) Or you can move it into a struct that gets returned (more 
> involved):
[...]

3) Put a struct on the heap that acts as the closure:

----
auto below5(size_t n, S s = S.init)
{
     import std.algorithm.mutation: moveEmplace;

     static struct ExplicitClosure
     {
         S s;
         bool pred(size_t _) { return _ < s; }
     }
     auto myClosure = new ExplicitClosure(s.move());
     auto pred = &myClosure.pred;
     return 0.iota(n).filter!pred;
}
----

This is the one I was trying to think of, but I got lost along 
the way.

I'm not sure if the code is really correct, because thinking 
about delegates being passed in template (alias) parameters 
confuses me.

If this is ok, it should make only the one explicit `new` 
allocation. No closure should be created for the `filter` call.

If passing `&closure.pred` like that is not ok, I'm lost again as 
for how one might construct an alternative to a closure.


More information about the Digitalmars-d-learn mailing list