Understanding Safety of Function Pointers vs. Addresses of Functions

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 12 18:51:28 PDT 2015


On Sunday, 12 July 2015 at 22:26:44 UTC, anonymous wrote:
>
> You don't need the lambda, do you? -> return x.map!fun.array;
>

You're right.

>
> 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 .. $])();
>     }
> }
> ----

Sorry, I don't think I made myself clear enough. Your code allows 
you to do something like call multiple functions in a loop. I'm 
talking about the fact that

alias cos = givemeabettername!(std.math.cos);
alias sin = givemeabettername!(std.math.sin);

are just two functions of many in std.math. Suppose I wanted to 
write it so that every function in std.math had an array version 
generated by this code. I would be repeating this alias line once 
each time. My point is that I don't see a way to do this in a 
loop. I don't think I can do something like

void callThemAll(functions ...)()
{
     foreach(f; functions)
     {
         alias __Function__ = givemeabettername!(f); //where 
__Function__ is the name of the function for f, not callThemAll
     }
}

callThemAll(std.math.cos, std.math.sin);

void main()
{
     real[] x = [0, PI];
     auto y = cos(x);
     auto z = sin(x);
}


More information about the Digitalmars-d-learn mailing list