Address of a lambda
FoxyBrown via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 7 10:33:33 PDT 2017
In gtk, we routinly have to use delegates for callbacks. But the
methods that accept these delegates want the address of the
delegate, 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?
Fine:
void main()
{
bool windowDelete(Event event, Widget widget) { Main.quit();
return false; }
MainWindow.addOnDelete(&windowDelete);
}
Invalid:
void main()
{
MainWindow.addOnDelete(&((Event event, Widget widget)
{ Main.quit(); return false; }));
}
and yet, the only difference is a copy and paste(i.e., a rewrite
rule, at most). Surely the compiler can figure out that we can
take such an address because anything that actually exists must
have an address somewhere. Seems like an arbitrary blocker? Even
if it saves us from some obscure problems, it should work in most
cases and be allowed when used in those cases.
What's even stranger is that the function windowDelete must be
declared in some type of object, such as another function, so it
is actually a delegate, if one has it in the module root then it
is a normal function and cannot be passed to addOnDelete, even
though, again, there is very little difference.
Invalid:
bool windowDelete(Event event, Widget widget) { Main.quit();
return false; }
void main()
{
MainWindow.addOnDelete(&windowDelete);
}
I do know the difference between a delegate and a function, and I
suppose addOnDelete should be defined to take a function instead?
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?
And aside, shouldn't all functions really be delegates? Having a
closure of the outer scope still holds at the module root
level(the scope is the module root). While it's an extra argument
to pass, it could simplify live a bit. The corner cases could be
handled by explicitly forcing it to be a function.
More information about the Digitalmars-d-learn
mailing list