Checking if CTFE is used?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Wed Dec 19 06:18:24 UTC 2018
On Tuesday, December 18, 2018 9:20:11 AM MST berni via Digitalmars-d-learn
wrote:
> On Tuesday, 18 December 2018 at 14:32:29 UTC, Adam D. Ruppe wrote:
> > CTFE is used if and only if it MUST be used by context. That's
> > a runtime function, so no ctfe.
> >
> > Do something like:
> >
> > int[4] generate() {
> >
> > int[4] tmp;
> > foreach(i; 0..4) tmp[i] = i;
> > return tmp;
> >
> > }
> >
> >
> > static immutable int[4] clue = generate();
>
> Great, that worked. :-) My reasoning was, that CTFE is somewhat
> greedy, that is, everything that can be evaluated at compile time
> will be evaluated at compile time...
>
> Many thanks for your replies. :-)
It's pretty much the opposite. CTFE is only ever done when the compiler
needs the result at compile-time, and it's never done as an optimization, if
nothing else because the compiler has no way of knowing whether the function
is even CTFE-able until it actually tries. Having it attempt CTFE in a bunch
of places and then give up (to then call the function at runtime instead)
would likely have a very negative impact on compilation time - especially
since CTFE isn't very efficient at the moment (though whenever the newCTFE
that Stefan is working on finally lands, that should improve significantly).
As things stand, you have complete control over when CTFE occurs, and it's
usually pretty easy to figure out if it's happening or not. As long as you
understand which things must be known at compile-time, it's straightforward.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list