Address of a lambda

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 7 10:52:25 PDT 2017


On 07/07/2017 10:33 AM, FoxyBrown wrote:
 > In gtk, we routinly have to use delegates for callbacks. But the methods
 > that accept these delegates want the address of the delegate,

I'm not a user but I don't think it's right. According to the following, 
it takes a delegate:

 
https://github.com/gtkd-developers/GtkD/blob/42ef854f7cd975519926900fe326e220410c028a/demos/gtkD/DemoMultiCellRenderer/DemoMultiCellRenderer.d#L124

wnd.addOnDelete( delegate bool (Event event, Widget widget) {
         widget.destroy();
         Main.quit();
         return false;
});

 > this
 > prevents us from being able to pass a lambda in directly, but there
 > really is not reason why we shouldn't be able to do this?

I think that's because the lambda is a 'function' if can be for 
efficiency reasons.

 > Invalid:
 >
 > void main()
 > {
 > MainWindow.addOnDelete(&((Event event, Widget widget) {    Main.quit();
 > return false; }));
 > }

It makes it very difficult to help if there is no code that demonstrates 
the problem. Here is my attempt and a solution with the addition of the 
keyword 'delegate':

alias Event = int;
alias Widget = int;

struct MainWindow {
     static void quit() {
     }

     static void addOnDelete(bool delegate(Event, Widget)) {
     }
}

MainWindow Main;

void main() {
     // ADDED 'delegate':
     MainWindow.addOnDelete(delegate (Event event, Widget widget) {
             Main.quit(); return false;
         });
}

So, there is no need to take the address of a lambda. It's already 
either a 'function' or a delegate.

 > I
 > suppose addOnDelete should be defined to take a function instead?

That would limit the users if they wanted to maintain state for the 
function.

 > But
 > how can we create a "delegate function" similar to the nested delegate
 > in the first case that works so that we can pass them as delegates?

Being explicit like above is one way. There is also toDelegate:

   https://dlang.org/phobos/std_functional.html#toDelegate

 > And aside, shouldn't all functions really be delegates?

Not in a system language like D that tries to avoid unnecessary cost. :)

Ali



More information about the Digitalmars-d-learn mailing list