Getting around the lack of foreach in CTFE

Dicebot public at dicebot.lv
Fri Mar 28 06:49:57 PDT 2014


On Friday, 28 March 2014 at 11:59:47 UTC, Colin Grogan wrote:
> I'm interested to hear peoples methods for getting around the 
> lack of foreach loops while using CTFE?
>
> Currently, I've been using a lot of recursive templates, but 
> its beginning to give me a headache and I'd like to see if 
> there's better ways around it.
>
> On a related note, is there plans to add foreach support to 
> CTFE?

Looks like you mix the terminology here. CTFE is "Compile-Time 
Function Evaluation" and means exactly that - interpretation of 
normal D function during compile-time. Of course, you can use 
foreach as usual inside those.

You post implies that you in fact ask about generic compile-time 
algorithms over compile-time argument lists, which is _not_ the 
same as CTFE. Indeed, lack of static declarative foreach causes 
lot of pain during meta-programming.

Relatively common pattern to avoid recursive template horror is 
to use private CTFE function inside the template:

template Stuff(T...)
{
     private string doStuff()
     {
         string result;
         foreach (Index, Arg; T)
         {
             // compute value or generate D code
         }
         return result;
     }

     enum Stuff = doStuff();
     // ..or for complex code-generating things:
     mixin(doStuff());
}


More information about the Digitalmars-d-learn mailing list