templatized delegate

Alex via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 22 14:07:20 PDT 2017


On Monday, 22 May 2017 at 20:38:27 UTC, Dukc wrote:
> On Monday, 22 May 2017 at 09:04:15 UTC, Alex wrote:
>> 2. Now, I want to store the delegate in another struct. If I 
>> want to do this, I have to define the pointer as static. This 
>> is not intended at the beginning, but it's ok, as I know, that 
>> the delegate would be the same across all instances of B.
>
> The reason it does not work with a non-static member is that A 
> generated has no way of knowing where B that contains the 
> delegate to be called resides. But it works when done this way:
>
> struct A(alias dg)
> {
>     auto fun(T...)(T params)
>     {
>         return dg(params);
>     }
> }
>
> struct B
> {
>     A!((B b, int i, string a) => b.dlgptr(i, a)) a;
>     void delegate(int, string) dlgptr;
>     this(void delegate(int, string) dlg)
>     {
>         dlgptr = dlg;
>     }
>     void fun(int i, string s)
>     {
>         a.fun(this, i, s);
>     }
> }
>
> void main()
> {
>     auto dlg(int i, string s)
>     {
>         import std.stdio;
>         writeln(i, " ", s);
>     }
>     auto b = B(&dlg);
>     b.fun(5, "a");
> }
>
> I wasn't in mood to look at C though, so I don't know if this 
> helps.

Yes, it does :)
The step to the C variant is, how to rewrite the lines

A!((B b, int i, string a) => b.dlgptr(i, a)) a;
and
this(void delegate(int, string) dlg)

if I want to define my delegate as a template:

template dlgptr(T, U...)
{
     void delegate(T, U) dlgptr;
}


More information about the Digitalmars-d-learn mailing list