Enum and CTFE function call
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Aug 14 10:21:54 UTC 2018
On Tuesday, August 14, 2018 3:12:30 AM MDT ixid via Digitalmars-d-learn
wrote:
> This will not compile as it says n is not known at compile time:
>
> auto fun(int n) {
> static foreach(i;0..n)
> mixin(i.to!string ~ ".writeln;");
> return;
> }
>
> enum value = 2;
>
>
> void main() {
> fun(value);
> }
>
> But making it a template parameter fun(int n)() and fun!value
> will obviously work as will replacing n in the foreach statement
> with the enum 'value'. It seems like a missed opportunity that
> the enum nature of 'value' does not propagate through the
> function call letting the compiler know that 'value'and therefore
> n are known at compile time.
The fact that value is an enum is irrelevant. fun(value) is a call at
runtime. CTFE is only triggered if the result must be known at compile time.
So, no matter what you pass to fun, fun is not going to be called at
compile-time unless the result is required at compile-time - e.g. if it's
used to initialize an enum, static variable, or member variable, or if it's
used as a template argument.
Inside of fun, n is used as in static foreach, which won't work regardless
of whether fun is called at compile-time or not, because n is a function
argument, not a template argument and is thus a "runtime" value even if the
functions is called at compile-time.
If you want n to be usable in the static foreach, then it cannot be a
function parameter. If it's an argument to the function, it must be a
template argument.
I suggest that you read this article:
https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time
It's a work in progress, but it should give you some insight into CTFE.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list