Is it possible to use a template to choose between foreach and foreach_reverse?

Mihail K via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 4 08:43:01 PDT 2016


On Saturday, 4 June 2016 at 14:32:23 UTC, pineapple wrote:
> It would be fantastic if I could write this -
>
>     static if(forward){
>         foreach(item; items) dostuff();
>     }else{
>         foreach_reverse(item; items) dostuff();
>     }
>
> as something like this -
>
>     foreach!forward(item; items) dostuff();
>
> Is there any way to accomplish this?

As far as I recall, foreach_reverse is deprecated in favour of 
range operations.
ie.

   import std.algorithm, std.range;

   static if(forward)
   {
       items.each!(item => doStuff());
   }
   else
   {
       items.retro.each!(item => doStuff());
   }

As for your question, I suggest writing a range function that 
calls retro conditionally. Something like,

   items.direction!(forward).each!(item => doStuff());


More information about the Digitalmars-d-learn mailing list