On Thursday, 30 March 2017 at 18:21:43 UTC, Enigma wrote:
I am using foreach and it seems to be done dynamically as I can
step through the code for each value and see them change. This
tells me it is not done at compile time like it should be.
Remember two facts:
1) CTFE is never done unless it specifically must be done
and
2) D does not have static foreach, it is just regular foreach
And a third warning:
* enum foo = [1,2,3]; makes foo work just like an array
literal... which means it actually does a runtime allocation
every time you reference it. Rarely what you actually want!
The answer is simple though: write an ordinary function that does
your calculation and pass it an ordinary array, but set it to a
static immutable array to force CTFE.
int getMax(int[] X) {
int y = 0;
foreach(x; X)
y = max(x, y);
return y;
}
void main() {
enum y = getMax([1,2,3,4,5]); // safe for int
static immutable y = getMax(...); // use that if return array
}
So you need to do a regular loop in a regular function, then
assign the result of that regular function to enum or static.