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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 4 10:25:46 PDT 2016


On 06/04/2016 07:32 AM, 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?

I agree with Mihail K. that retro() should be preferred. However, some 
iteration like tree iteration can be simpler with the function call 
stack, which opApply and opApplyReverse automatically take advantage of.

enum Direction {
     forward, backward
}

void foo(Direction dir = Direction.backward)() {
     static if (dir == Direction.forward) {
     } else {
     }
}

void main() {
     foo!(Direction.forward)();
     foo!(Direction.backward)();
     foo();
}

Ali



More information about the Digitalmars-d-learn mailing list