CTFE and Static If Question

jmh530 john.michael.hall at gmail.com
Thu May 7 15:00:18 UTC 2020


I am curious how ctfe and static ifs interact. In particular, if 
an enum bool passed as a template parameter or run-time one will 
turn an if statement into something like a static if statement 
(perhaps after the compiler optimizes other code away). In the 
code below, I am a function that takes a bool as a template 
parameter and another that has it as a run-time parameter. In the 
first, I just pass an compile-time bool (y0) into it. In the 
second I have run-time (x0) and compile-time (y0).

Does foo!y0(rt) generate the same code as foo(rt, y0)?

How is the code generated by foo(rt, x0) different from 
foo(rt,y0)?

auto foo(bool rtct)(int rt) {
     static if (rtct)
         return rt + 1;
     else
         return rt;
}

auto foo(int rt, bool rtct) {
     if (rtct == true)
	    return rt + 1;
     else
         return rt;
}

void main() {
     int rt = 3;
     bool x0 = true;
     bool x1 = false;
     assert(foo(rt, x0) == 4);
     assert(foo(rt, x1) == 3);

     enum y0 = true;
     enum y1 = false;
     assert(foo!y0(rt) == 4);
     assert(foo!y1(rt) == 3);
     assert(foo(rt, y0) == 4);
     assert(foo(rt, y1) == 3);
}




More information about the Digitalmars-d-learn mailing list