callback craziness

Engine Machine via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 7 13:01:10 PDT 2016


I use callbacks a lot and have trouble with D in a nogc context.

First, I cannot declare the parameters with a nogc or I get a 
compile time error.

@nogc void foo(void delegate(int x) @nogc f);

fails with the @nogc.

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

@nogc void foo(void function(int x) f);

Works, but f then cannot access the context.

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.

But if I define the lambda outside it works:

auto f = (int x, string s) { };
foo!string(f, 1);

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?


alias callback(Args) = @nogc void function(string, int, Args);
@nogc public void foo(Args...)(callback!Args c, auto ref Args 
args, int extra = 0)
{
    ...
}
		
auto f = (string s, int l) @nogc
{
     printf("%s\n", s.ptr);
};
foo(f, 1);

or

auto f = (string s, int l, string x) @nogc
{
     printf("%s\n", x.ptr);
};
foo!string(f, "Test string", 1);

which is the case that work sin mine code. But I don't always 
want to have to pass stuff.

Any ideas? I realize the code is messy. You'll have to read 
between the lines.



So, the two problems I have is that I would like to be able to 
add a @nogc callback inline and to be able to pass no arguments.




More information about the Digitalmars-d-learn mailing list