a lambda with arguments has type void?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 7 15:17:03 PDT 2016


On 06/08/2016 12:02 AM, cy wrote:
> import std.stdio;
>
> void foo(Callable)(Callable bar) {
>    bar();
> }
>
> void foo2(Callable)(Callable bar, int baz) {
>    bar(baz);
> }
>
> void main() {
>    foo({
>        writeln("okay");
>      });
>    foo2((bar) {
>        writeln("got",bar);
>      },42);
>    foo2((bar) => writeln("yay",bar), 42);
> }
>

You don't specify the types of the parameters of the function literals, 
so you effectively have templates there. As such the literals have no 
types, and can't be passed as arguments. That they're called with an int 
in foo2's body is not taken into consideration at that point.

You can:
* make it `int bar` in the literals, or
* explicitly take a `void delegate(int)` or `void function(int)` in foo2, or
* take the callback as a "template alias parameter":
----
import std.stdio;
void foo2(alias bar)(int baz) { bar(baz); }
void main() {
   foo2!((bar) { writeln("got", bar); })(42);
   foo2!(bar => writeln("yay", bar))(42);
}
----


More information about the Digitalmars-d-learn mailing list