CTFE and Static If Question
ag0aep6g
anonymous at example.com
Thu May 7 15:34:21 UTC 2020
On 07.05.20 17:00, jmh530 wrote:
> 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);
> }
The `static if` is guaranteed to be evaluated during compilation. That
means, `foo!y0` effectively becomes this:
auto foo(int rt) { return rt + 1; }
There is no such guarantee for `foo(rt, y0)`. It doesn't matter that y0
is an enum.
But a half-decent optimizer will have no problem replacing all your
calls with their results. Compared with LDC and GDC, DMD has a poor
optimizer, but even DMD turns this:
int main() {
int rt = 3;
bool x0 = true;
bool x1 = false;
enum y0 = true;
enum y1 = false;
return
foo(rt, x0) +
foo(rt, x1) +
foo!y0(rt) +
foo!y1(rt) +
foo(rt, y0) +
foo(rt, y1);
}
into this:
int main() { return 21; }
More information about the Digitalmars-d-learn
mailing list