digitalmars.D.learn - Why function does not work with delegate
- Alex (26/26) May 22 2019 In gtkD one can use a lambda directly:
- H. S. Teoh (8/23) May 22 2019 [...]
- Adam D. Ruppe (5/8) May 22 2019 Because you didn't ask for one and it didn't have to be.
- Alex (3/12) May 23 2019 That is what I was looking for.
In gtkD one can use a lambda directly:
X.addOnButtonPress((GdkEventButton* e, Widget w) ...
but if I try move the lambda in to a variable so I can use it
with multiple handlers, I get an error:
// x is a function and does not work
auto x = (GdkEventButton* e, Widget w) ...
X.addOnButtonPress(x);
etc...
It's because the second case treats x as a function while the
first it is a delegate and addOnButtonPress requires a delegate...
Why is x not a delegate?
Now, if I reference a variable outside the scope of the lambda it
turns magically in to a delegate and works!
But that is an ugly hack!
// now x is a delegate and works
auto x = (GdkEventButton* e, Widget w) { auto q = X; ...
Now sure I can hack x and use some template to turn it in to a
fake delegate but then that is dangerous.
I suppose one could have a template that only converts it if it
is a function and then that will deal with both cases and might
work...
But why?
Is there any way to force it to not reduce the delegate to a
function which is obviously an optimization when nothing accesses
the outside context.
May 22 2019
On Wed, May 22, 2019 at 10:33:52PM +0000, Alex via Digitalmars-d-learn wrote:
In gtkD one can use a lambda directly:
X.addOnButtonPress((GdkEventButton* e, Widget w) ...
but if I try move the lambda in to a variable so I can use it with
multiple handlers, I get an error:
// x is a function and does not work
auto x = (GdkEventButton* e, Widget w) ...
X.addOnButtonPress(x);
etc...
It's because the second case treats x as a function while the first it
is a delegate and addOnButtonPress requires a delegate...
[...]
You could try explicitly declaring it as a delegate:
void delegate(GdkEventButton*, Widget) x = (e, w) { ... };
X.addOnButtonPress(x);
T
--
I am Ohm of Borg. Resistance is voltage over current.
May 22 2019
On Wednesday, 22 May 2019 at 22:33:52 UTC, Alex wrote:
auto x = (GdkEventButton* e, Widget w) ...
X.addOnButtonPress(x);
Why is x not a delegate?
Because you didn't ask for one and it didn't have to be.
Just add the delegate keyword to ask for one:
auto x = delegate(GdkEventButton* e, Widget w) {};
^^^^^^^^
May 22 2019
On Wednesday, 22 May 2019 at 23:54:47 UTC, Adam D. Ruppe wrote:On Wednesday, 22 May 2019 at 22:33:52 UTC, Alex wrote:That is what I was looking for. Thanks.auto x = (GdkEventButton* e, Widget w) ... X.addOnButtonPress(x); Why is x not a delegate?Because you didn't ask for one and it didn't have to be. Just add the delegate keyword to ask for one: auto x = delegate(GdkEventButton* e, Widget w) {}; ^^^^^^^^
May 23 2019









"H. S. Teoh" <hsteoh quickfur.ath.cx> 