callback craziness

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 7 13:48:29 PDT 2016


On 08/07/2016 10:01 PM, Engine Machine wrote:
> @nogc void foo(void delegate(int x) @nogc f);
>
> fails with the @nogc.

Compiles just fine for me.

> 2nd, I cannot use a delegate because of the @nogc context,

Delegates don't necessarily need a GC allocation. They only need it when 
they need a closure. Delegates of methods don't need closures. And when 
you pass the delegate in a `scope` parameter, no closure is needed, either.

[...]
> So, to get around these problems, I have to do something like this:
>
> alias callback(Args) = @nogc void function(int x, Args);
> @nogc void foo(Args...)(callback!Args f, auto ref Args args, int extra = 0)
>
> The problem with this is that I can't seem to add f inline:
>
> foo!string((int x, string s) { }, 1);
>
> this fails with template mismatch.

You're missing an argument there. The second parameter of foo is `args` 
which is `string` here. This call works:

     foo!string((int x, string s) { }, "", 1);

> But if I define the lambda outside it works:
>
> auto f = (int x, string s) { };
> foo!string(f, 1);

Doesn't work for me. Still missing the string argument.

> The problem with this is that when I want to pass no arguments,
>
> auto f = (int x) { };
> foo(f, 1);
>
> fails. It seems that Args... requires at least one argument to match the
> template? This may be a bug?

One thing you need to fix: The `callback` template needs a template 
sequence parameter (i.e. `Args...`). Otherwise it takes exactly one type.

That doesn't make it work, though. You also need to add empty template 
instantiation parentheses (i.e. `foo!()`), and you need to remove `auto 
ref` from the `args` parameter.

No idea why it doesn't work with `auto ref`. At least that part looks 
like a bug to me.


More information about the Digitalmars-d-learn mailing list