Understanding Safety of Function Pointers vs. Addresses of Functions
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 12 15:26:42 PDT 2015
On Sunday, 12 July 2015 at 21:07:34 UTC, jmh530 wrote:
> private template givemeabettername(alias fun)
> {
> T givemeabettername(T : U[], U)(T x)
> if (isArray!(T))
> {
> return x.map!(a => fun(a)).array;
You don't need the lambda, do you? -> return x.map!fun.array;
> }
> }
>
> Very cool. I guess I'm still left with the issue that I don't
> know how to loop through a bunch of different functions at
> compile time, but this is so elegant that it doesn't seem like
> that big a deal.
I don't know what exactly you're after, but you can use foreach
on a whatever-they're-called-now tuple (there's been a discussion
about the name which I haven't followed; I mean the kind you get
from a TemplateTupleParameter):
----
void f1() {}
void f2() {}
void callThemAll(functions ...)()
{
foreach(f; functions) /* The loop is unrolled at compile
time. */
{
f();
}
}
void main()
{
callThemAll!(f1, f2)();
}
----
As usual, recursion is an alternative:
----
void callThemAll(functions ...)()
{
static if(functions.length > 0)
{
functions[0]();
callThemAll!(functions[1 .. $])();
}
}
----
More information about the Digitalmars-d-learn
mailing list