On 03/30/2017 11:21 AM, Enigma wrote:
> Is it possible to compute at compile time computations on a manifest
> constant that contains values(in a somewhat complex way, but that
> shouldn't matter)?

You can do anything that you want as long as it's available at compile time. For example, you cannot interact with a user.

> 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.

D does not have an explicit way of requesting compile-time execution. It's done when it's needed at compile time:

- enum values

- static const values

- Template arguments

- Mixin code

In order to prove yourself that something is computed at compile time, just use pragma(msg).

> import std.meta, std.algorithm, std.stdio;
> void main()
> {
>     enum X = [1,2,3,4,5];

One big gotcha with enum arrays is that every place that you refer to X, a temporary array will be created dynamically. Only the manifest value of the array is computed at compile time. Try the following code and be surprised that it prints two different addresses:

    writeln(X.ptr);
    writeln(X.ptr);

(This issue does not apply to strings.)

So, what you want to do is to create an enum like the above, but use it only once at runtime to initialize another array, likely immutable, for your actual use.

// This is what the program will actually use
immutable int[] X;

auto calculateArray() {
    return [1,2,3,4,5];
}

// This is used only once to initialize X
private enum X_ = calculateArray();
pragma(msg, "Known at compile time: ", X_);

import std.algorithm: maxElement;
enum y = maxElement(X_);

shared static this() {
    X = X_;
}

void main() {
    pragma(msg, "Known at compile time: ", y);
}

Ali

Reply via email to