Cannot use function as foreach aggregate.

Russell Lewis webmaster at villagersonline.com
Wed Apr 4 12:21:44 PDT 2007


Jarrett Billingsley wrote:
> RetType delegate(Args) ToDelegate(RetType, Args...)(RetType function(Args) 
> func)
> {
>     struct S
>     {
>         RetType function(Args) func;
> 
>         RetType callMe(Args args)
>         {
>             return func(args);
>         }
>     }
> 
>     S* s = new S;
>     s.func = func;
>     return &s.callMe;
> }

What you give above is the good, general solution, which allows you to 
save the resulting delegate, or return it from the function, or 
whatever.  But in cases where the delegate won't be used outside of the 
current function, it's simpler to use a delegate literal:

void myFunc() {
   int function(int delegate(inout Type)) myAggregateFunc = <whatever>;
   int delegate(int delegate(inout Type)) myAggregateDelegate =
         delegate int(int delegate(inout Type) dg)
                 { return myAggregateFunc(dg); }

   foreach(Type myVar; myAggregateDelegate)
       { <body> }
}



More information about the Digitalmars-d mailing list