identify literals
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Fri Jan 24 11:13:04 UTC 2025
On Friday, January 24, 2025 3:50:15 AM MST Dom DiSc via Digitalmars-d-learn wrote:
> Is it possible in D to find out if the parameter given to a
> function is a literal or a compile time constant?
Not when calling the function, no. It should be possible to test whether a
particular argument is a known at compile time by writing an is expression
that uses it in a context where it must be known at compile time, since if
the result compiles and results in a type other than void, then the value is
known at compile time, and if you get void (and thus the is expression is
false), then it isn't known at compile time. However, that would have to be
tested separately from the function call. The function itself doesn't care
about its arguments at all once it's been compiled. It just takes them and
runs whether that's part of CTFE or at runtime. The function itself is the
same regardless of what you pass to it.
> Of course, if it has _only_ parameters known at compile time, the
> function will be executed during CTFE, so I can check for the
> execution time. But if it has also runtime-parameters, it will
> only be executed during runtime. Is it still possible to find
> out, which values are known at compile-time?
No. For a function to be called with CTFE, it must be used in a context
where the result must be known at compile time - e.g. providing the value of
an enum or directly initializing a member variable. In such a case, the
arguments to the function must also be known at compile time, or you'll get
a compilation error, but if you call a function entirely with arguments that
are known at compile time, but it's not called in a context where the result
must be known at compile time, then it will be called at runtime.
> They should be immutable, but do they have some other, more
> specific property?
Immutability is not a requirement for CTFE.
I suggest that you read this article:
https://wiki.dlang.org/Compile-time_vs._compile-time
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list