Cannot use function as foreach aggregate.

BCS BCS at pathlink.com
Thu Apr 5 09:12:18 PDT 2007


Jarrett Billingsley wrote:
> 
> Not quite.. you can't alias addresses, and I don't think you can pass 
> function pointers as template arguments (though I might be wrong).
> 
> Though using your idea of a single static instance of the struct, my 
> function can then become:
> 
> RetType delegate(Args) ToDelegate(RetType, Args...)(RetType function(Args) 
> func)
> {
>     struct S
>     {
>         static S s;
>         static RetType function(Args) func;
> 
>         RetType callMe(Args args)
>         {
>             return func(args);
>         }
>     }
> 
>     S.func = func;
>     return &S.s.callMe;
> }
> 
> Which is pretty sweet, as it no longer requires a heap allocation with each 
> call. 
> 
> 

I don't think that will work. It will only allow one delegate per 
function type.

int foo(int i){return 1;}
int bar(int i){return 2;}

auto a = ToDelegate!(int, int)(foo);
auto b = ToDelegate!(int, int)(bar); // stomps on a;

a(1); // should return 2 when 1 is expected


also it occurs to me that there is no reason that the addressOf is 
needed. If functions as args works (I think it does) then this should work:

template ToDelegate(RetType, RetType function(Args) func, Args...)
{
     struct S
     {
         static S s
         RetType callMe(Args args)
         {
             return func(args);
         }
     }
     alias S.s.callMe ToDelegate;
}

if that doesn't work than this might:

template ToDelegate(RetType, alias func, Args...)

but it might have problem with overloaded functions.



More information about the Digitalmars-d mailing list