On 8/4/21 11:20 PM, H. S. Teoh wrote:
On Thu, Aug 05, 2021 at 01:39:42AM +0000, someone via Digitalmars-d-learn wrote:
[...]
What happens in the following case ?

public immutable enum gudtLocations = [
    r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, r"ART"d),
    r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
    r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, r"CET"d),
    r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
    r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
    ];

This is something that I also need at compilation time.
[...]

If you need a constant array value both at compile-time and runtime, one
way to do it is to declare an enum that is used only by compile-time
code, and the same enum is used once to declare the runtime static
immutable.

A static immutable *array* is usable at compile time. No need for the enum.


Example:

        enum ctValue = [ "my", "data", "here", ... ];

        // Initialize this once with ctValue.
        static immutable string[] rtValue = ctValue;

        if (ctfe) {

`if(__ctfe) {`

                // Compile-time: use ctValue
                foreach (value; ctValue) {
                        ...
                }
        } else {
                // Runtime: use rtValue instead
                foreach (value; rtValue) {
                        ...
                }
        }

Just be sure you don't use ctValue during runtime, otherwise it will
incur an allocation per use.

H.S. Teoh, I know you know better than this ;) None of this is necessary, you just need `rtValue` for both runtime and CTFE (and compile time parameters)!

Now, the original question is about *associative arrays*, which are a different animal. Those, you actually have to initialize using a static constructor, and does indeed need both an enum and a static immutable, as CTFE currently does not understand runtime AAs. This is a huge issue since you do need silly things like the `if(__ctfe)` statement you wrote, and keep an enum handy for those cases which is identical to the static immutable. We really need to fix this.

-Steve

Reply via email to