Understanding Safety of Function Pointers vs. Addresses of Functions

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 14 05:12:40 PDT 2015


On Tuesday, 14 July 2015 at 01:05:21 UTC, jmh530 wrote:
> Note: some of the above seemed to only work when I kept the 
> std.math.cos, std.math.sin text in there. When I take it out, I 
> get warnings about recursive aliases.

Yeah, you can't do `alias cos = givemeabettername!cos;`. That 
would define the new cos in terms of itself.

> But, I can't seem to use a foreach loop. The recursive mixin 
> template seems to be required.

You can only use the implicitly static foreach where the normal, 
dynamic foreach is allowed, i.e. in function bodies. This is a 
syntactic restriction. If we had `static foreach` (like we have 
`static if`), that would presumably work everywhere.

>
> So this is the last thing I did (that didn't work). Adding foo 
> back to the alias works.
>
> mixin template callThemAll(functions...)
> {
>    mixin("alias " ~__traits(identifier, functions[0]) ~
> 		  " = givemeabettername!(std.math."~__traits(identifier, 
> functions[0]) ~ ");");
>     static if(functions.length >1)
>    		mixin callThemAll!(functions[1..$]);
> }
>
> mixin callThemAll!(cos, sin);

Works for me. Please show the complete code and the error message 
you get.

Here's what works for me:
----
import std.algorithm: map;
import std.math;
import std.array: array;

template givemeabettername(alias fun)
{
     T givemeabettername(T : U[], U)(T x)
     {
         return x.map!fun.array;
     }
}

mixin template callThemAll(functions...)
{
     mixin("alias " ~__traits(identifier, functions[0]) ~
         " = givemeabettername!(std.math."~__traits(identifier, 
functions[0]) ~ ");");
     static if(functions.length >1)
         mixin callThemAll!(functions[1..$]);
}

mixin callThemAll!(cos, sin);

void main()
{
     real[] a = [1, 2, 3];
     auto c = cos(a);
     auto s = sin(a);
}
----


More information about the Digitalmars-d-learn mailing list