Search code examples
compilationruntimedpure-function

Pure D function to be calculated at run time (not compile time)


I am curious: If there is a pure D function, it can be calculated at compile time.

What if I do not want a pure function to be calculated at compile time, but to calculate it at run time, how to do it?

Example:

static int result = f();

f is a pure function and I want it to calculate at run time.


Solution

  • FYI, not all pure functions can be calculated at compile time, and being pure is no requirement to be compile time run. They actually have very little to do with each other.

    Compile time function evaluation is attempted for ANY function, but ONLY when it MUST be. This is determined by context - must the answer be there at compile time? This is true for:

    • enum values
    • static initializers
    • static if conditions
    • static foreach argument
    • template arguments

    If you thus want it at runtime, just call it outside one of these contexts.

    static int result = f();
    

    The above is a static initializer, thus CTFE.


    static int result;
    result = f();
    

    This is no longer a static initializer, thus no CTFE. To keep it from being called twice, you can just put a regular if check on it with a special value meaning it isn't run yet or with a separate bool flag.

    If this is at module scope, use a constructor:

    static int result;
    static this() { result = f(); }