Static Foreach + Marking "compile time" variables

Simen Kjærås simen.kjaras at gmail.com
Wed Mar 28 08:05:55 UTC 2018


On Wednesday, 28 March 2018 at 07:45:59 UTC, Chris Katko wrote:
> I have a static foreach that goes through the parameter list 
> and if it sees a class like "rotate", ideally, I want it to 
> mark a boolean "has_rotate=true"
>
> Then simply later on, once I've parsed the list, I pick an 
> output path:
>
>     static if(has_rotate && has_position && has_scale)
>     {
>     //call C function al_draw_rotated_scaled_bitmap(...);
>     }
>
> So I pass a bunch of "options" and then based on those options, 
> it picks the right function to call instead of me manually 
> writing 
> draw_fixed_centered_rotated_scaled_colored_compressed_bitmap() 
> manually.
>
> The problem is, I can foreach through those parameters all just 
> fine... but I can't "set" a marker.
>
> The error message makes perfect sense in retrospect:
>
>      variable has_position cannot be read at compile time
>
> has_position isn't a static/compile-time variable. The question 
> is... do they exist in D? Because otherwise, I'll be going from 
> a really clean, elegant solution that simply passes through 
> each parameter, and then reacts to the combined result, and end 
> up with something that has to "step toward" the result, or 
> perhaps, test every possible permutation individually--so as to 
> not need variables.

D does not have compile-time variables. The way you'd generally 
do what you describe is with the templates in std.meta. Instead 
of something like this:

     bool hasRotate= false;
     static foreach (e; MyTuple) {
         hasRotate |= is(e == Rotate);
     }
     static if (hasRotate) { // Fails, since b is a runtime 
variable.
         // Stuff
     }

You'd be using a more functional style:

     template isa(T) {
         enum isa(U) = is(U == T);
     }

     enum hasRotate = anySatisfy!(isa!Rotate, MyTuple);
     static if (hasRotate) {
         // Stuff
     }

--
   Simen


More information about the Digitalmars-d-learn mailing list