Code example for function/delegate as template argument ?
Basile B. via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 4 00:25:07 PDT 2016
On Wednesday, 4 May 2016 at 06:21:36 UTC, chmike wrote:
> Hello,
>
> I failed to find some code example for a template class/struct
> that accept a function/delegate as template argument. All
> examples I could find use simple value types like int or double.
>
>
> I piggy bag another question. Defining a function/delegate as
> function argument is shown in examples. What I could not find
> is how would I pass an object instance with a method to call ?
> In C++ we use std::bind. How do we do that in D ?
As for the second question, finding the right method dynamically
(virtual method or interface) is easy so I suppose you want to
find a member using D reflection.
Here is a quick example:
----
struct Bar
{
void fun(string text) {text.writeln;}
}
struct Foo
{
void delegate(string) dg;
this(T)(T t)
{
foreach(member; __traits(allMembers, T))
{
foreach(i, overload; __traits(getOverloads, T,
member)[])
{
auto overloadDg = &__traits(getOverloads, t,
member)[i];
static if (is(typeof(overloadDg) == typeof(dg)))
{
dg = &__traits(getOverloads, t, member)[i];
break;
}
}
}
if (dg)
dg("found");
}
}
void main(string[] args)
{
Bar bar;
Foo foo = Foo(bar);
}
----
More checkings are possible. Here I just verify that a pointer to
a member function is of same type as the delegate to assign.
More information about the Digitalmars-d-learn
mailing list