Enum and CTFE function call

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Aug 14 11:25:06 UTC 2018


On Tuesday, August 14, 2018 4:03:11 AM MDT Michael via Digitalmars-d-learn 
wrote:
> The page does state that enums should trigger CTFE though.

CTFE is triggered when a value must be known at compile-time. So, if you
have something like

enum a = foo();

foo gets called at compile-time, because an enum's value must be known at
compile-time. So, in that sense, enums do trigger CTFE. However, using an
enum does not necessarily require CTFE. e.g.

void main()
{
    enum a = 42;
    auto result = foo(a);
}

uses an enum, but the enum is used in a runtime context. foo's result is
given to a local variable, which does not need to have its value known at
compile-time, so foo is not called at compile-time. The fact that the
argument to foo is known at compile-time is irrelevant. CTFE is all about
evaluating functions at compile-time when the result is used in a context
that must be known at compile-time. It isn't used in an attempt to optimize
code or attempted just because it might work. It's used because a function
is called in a context where the result is explicitly used at compile-time.
The most common situations would be template arguments and initializing
enums, static variables, and member variables.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list