templatized delegate
Alex via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 22 02:04:15 PDT 2017
Hi, all
I have a question, how to handle a templated delegate. However,
I'm not sure, if I'm going in the right direction, so I have
three examples, and my question is about the third.
1. Here, a struct with an alias is defined and on its creation
the delegate get known to the struct. Everything is ok.
struct A(alias dg)
{
auto fun(int i, string s)
{
return dg(i, s);
}
}
void main()
{
auto dlg(int i, string s)
{
import std.stdio;
writeln(i, " ", s);
}
auto a = A!dlg();
a.fun(5, "a");
}
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.
struct A(alias dg)
{
auto fun(int i, string s)
{
return dg(i, s);
}
}
struct B
{
A!dlgptr a;
static void delegate(int, string) dlgptr; // here, without the
"static" "need 'this' to access member dlgptr" rises
this(void delegate(int, string) dlg)
{
dlgptr = dlg;
}
void fun(int i, string s)
{
a.fun(i, s);
}
}
void main()
{
auto dlg(int i, string s)
{
import std.stdio;
writeln(i, " ", s);
}
auto b = B(&dlg);
b.fun(5, "a");
}
3. Now the hard stuff comes. I want to templatize my delegate.
struct A(alias dg)
{
auto fun(T, U...)(T t, U u)
{
return dg!(T, U)(t, u);
}
}
struct C
{
A!dlgptr a;
/* static? */ template dlgptr(T, U...)
{
/* static? */ void delegate(T, U) dlgptr;
}
this(???)
{
???
}
void fun(T, U...)(T t, U args)
{
dlgptr!(T, U)(t, args);
}
}
void main()
{
auto dlg(T, U...)(T t, U u)
{
import std.stdio;
writeln(t, " ", u);
}
auto c = C(???);
c.fun(5, "a"); // exception, obviously, as C is not initialized
properly
A!dlg a;
a.fun(5, "a"); //Error: function test92.A!(dlg).A.fun!(int,
string).fun cannot get frame pointer to test92.main.dlg!(int,
string).dlg
}
Here, nothing works any more... I have no idea, what to pass to
the struct C, as a template is not an lvalue. But even the direct
initialization of A doesn't work...
By the way, I found
http://forum.dlang.org/post/xiycyjndqzbohjtjfjvh@forum.dlang.org
and
http://www.digitalmars.com/d/archives/digitalmars/D/learn/delegate_template_and_alias_31092.html
these both go into the right direction I think... but don't see,
how to reformulate them...
Thanks in advance :)
More information about the Digitalmars-d-learn
mailing list