callback craziness

Engine Machine via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 7 15:08:42 PDT 2016


On Sunday, 7 August 2016 at 20:48:29 UTC, ag0aep6g wrote:
> 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.

Well, one can't pick the case the delegate is passed. When I use 
a delegate in the nogc context it errs.

> [...]
>> 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);
>

Yeah, that was just a typeo obvious. That's not the reason it 
fails.

>> 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.
>

Yes, same typo.

>> 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.

I did try that first and it didn't work. it works without ..., 
and I figured that it is a template parameter and can also 
represent a sequence? But I only tried with one argument so it 
worked.

I added ... but same problems.

> 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.


Yeah, so, this is typically what happens. One bug makes me change 
my tail for two hours ;/


More information about the Digitalmars-d-learn mailing list