Getting around the lack of foreach in CTFE

Colin Grogan grogan.colin at gmail.com
Fri Mar 28 07:42:51 PDT 2014


On Friday, 28 March 2014 at 13:49:59 UTC, Dicebot wrote:
> 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());
> }

Yeah, I am mixing the two up. Not sure what I was thinking 
before! Thanks for clarifying.

Im trying to parse command line args and then build a struct that 
will, at run-time, hold the data the user passed in via command 
line args.
Very similar to Pythons docopt utility -> 
https://github.com/docopt/docopt

Up till now, I've been using templates to do all of the work, but 
now that I realise I can do it all with functions I might try 
that. Then use a mixin template to create the struct with 
whatever data is required.

Thanks.
I'm sure I'll be back to bombard ye with questions soon!


More information about the Digitalmars-d-learn mailing list