Anonymous Delegates

Nick Sabalausky a at a.a
Mon Jun 16 12:06:15 PDT 2008


"Russell Lewis" <webmaster at villagersonline.com> wrote in message 
news:g35t4n$22n6$1 at digitalmars.com...
> Now you see that (in D2, which has full and automatic closure support), an 
> anonymous delegate is just another cool thing that can be passed:
>
> BEGIN CODE
>    SomeInterestingValue v = <whatever>;
>    SomeWindowClass w = GetSomeSpecificWindow();
>    b.addOnClicked_noArg({ w.setSomeProperty(v) });
> END CODE
>
> Note that in the above example, the 'this' pointer will point to the 
> automatically-allocated heap frame, which will store your 'v' and 'w' 
> variables, and when the delegate is called, that one-line function will be 
> executed.
>

In D1 and D2, what happens if you do something like this:

class MyClass
{
    int delegate() callback;

    void registerCallback(int delegate() callback)
    {
        this.callback = callback;
    }

    void display()
    {
        writefln("{0}", callback());
    }
}

void foo()
{
    int val;
    auto c = new MyClass();

    val = 1;
    c.registerCallback({ return val; })

    val = 2;
    c.display();  // Does this display "1" or "2"?
}

In D1 and D2, does that display "1" or "2"?

As long as I'm asking about delegate stuff, something else I've been 
wondering too: I know this following syntax for calling a function isn't 
supported, but is there any technical reason preventing it from being 
possible?:

// Note that the delegate is the last parameter:
void repeat(int times, int delegate() body)
{
    // BTW, is "auto" omittable here? I didn't
    // think so, but the example here omits it:
    // http://www.digitalmars.com/d/2.0/statement.html#ForeachRangeStatement

    for(auto i; 0..times)
        body();
}

void foo()
{
    // Current method of calling, ugly:
    repeat(7,
    {
        writefln("Calling Callback");
    });

    // Not currently allowed, but is it possibly doable?
    // Much nicer-looking.
    repeat(7)
    {
        writefln("Calling Callback");
    }
}

Sorry if I already brought that up before, I can't remember if I did or not.

Or, maybe for the sake of language consistency it could do something like 
this:

void myfunc(int a, int b, void delegate() foo1, void delegate() foo2, void 
delegate() foo3)
{
  // Do stuff
}

// Standard way:
myfunc(1, 2,
   { /+ do stuff 1 +/ },
   { /+ do stuff 2 +/ },
   { /+ do stuff 3 +/ });

// Crazy Fancy way inspired by the
// function contract "in{}out{}body{}" stuff:
myfunc()
foo1
{
    // do stuff 1
}
a: /+expression here+/,
b
{
    // Do stuff
    return /+expression here+/;
}
foo3
{
    // do stuff 3
}
foo2
{
    // do stuff 2
}





More information about the Digitalmars-d mailing list