Anonymous Delegates

Erik Lechak prochak at netzero.net
Mon Jun 16 03:59:29 PDT 2008


Hello all,

This is a trivial example that got me excited about delegates:

import std.stdio;

class Dog{
    string name;
    
    this( string name){
        this.name = name;
    }
    
    void printName(){
        writefln(name);
    }
}

int main(string [] args){
    Dog kippy = new Dog("kippy");
    void delegate() name = &kippy.printName;
    name();
    return 0;
}


Now for some real-world gtk stuff.  What does the anonymous delegate buy me in the next bit of code.  Even if it wasn't a super trivial callback, I don't know why it is better as a delegate than a function pointer.

Button b = cast(Button)g.getWidget("button1");
b.addOnClicked( delegate void(Button aux){ exit(0); } );

I found myself using the equivalent C code to connect the widget to the callback, but I want to do it the D ( or at least the gtkd ) way.  But it just seems to complicate the code without reason.

I though maybe I could do this:
b.addOnClicked( delegate void(Button aux){ 
    this.doSomethingAButtonCanDo(); 
} );

And somehow the the callback would populate the 'this' variable with the button that generated the callback.  But instead I get a compile-time error: Error: 'this' is only allowed in non-static member functions, not __dgliteral1.

So if anonymous delegates don't (can't) have an object associated with them, why do they exist if they are functionally equivalent to a function pointer?  Or are they not equivalent?  

Then I thought maybe I could cast a callback function to a delegate.  So at least at some point in the future the signal_autoconnect feature might work, and I could easily remove the manual registration of callbacks.  But I just get this error: conversion to non-scalar type requested.

void bc(Button a){
    writefln("adsf");
}

b.addOnClicked( cast( void delegate(Button)) &bc );

Then I read the following documentation:
  "If the keywords function or delegate are omitted, it defaults to being a delegate."
  "and the following where the return type int is inferred:"

And I saw this:
  int abc(int delegate(long i));
  void test()
  {   int b = 3;
     abc( (long c) { return 6 + b; } );
  }

And this:
   loop(5, 100, { d += 1; } );

Since delegates have a nice shorthand syntax, they must be more important than I realize. Without an associated object, they just sound like function pointers to me.

What am I missing?

Thanks,
Erik Lechak



More information about the Digitalmars-d mailing list