@@ -2181,10 +2181,45 @@ void main()
2181
2181
$(H2 $(LNAME2 interpretation, Compile Time Function Execution (CTFE)))
2182
2182
2183
2183
$(P Functions which are both portable and free of global side-effects can be
2184
- executed in Compile Time Function Execution. CTFE is subject to the
2185
- following restrictions:
2184
+ executed at compile time. In certain contexts, such compile time execution
2185
+ is guaranteed. It is called Compile Time Function Execution (CTFE) then.
2186
+ The contexts that trigger CTFE are:)
2187
+
2188
+ $(UL
2189
+ $(LI initialization of a static variable or a manifest constant)
2190
+ $(LI static initializers of struct/class members)
2191
+ $(LI dimension of a static array)
2192
+ $(LI argument for a template value parameter)
2193
+ $(LI $(D_KEYWORD static if))
2194
+ $(LI $(D_KEYWORD static foreach))
2195
+ $(LI $(D_KEYWORD static assert))
2196
+ $(LI $(D_KEYWORD mixin) statement)
2186
2197
)
2187
2198
2199
+ $(SPEC_RUNNABLE_EXAMPLE_COMPILE
2200
+ ---
2201
+ template eval( A... )
2202
+ {
2203
+ const typeof(A[0]) eval = A[0];
2204
+ }
2205
+
2206
+ int square(int i)
2207
+ {
2208
+ return i * i;
2209
+ }
2210
+
2211
+ void foo()
2212
+ {
2213
+ static j = square(3); // CTFE
2214
+ writeln(j);
2215
+ assert(square(4)); // run time
2216
+ writeln(eval!(square(5))); // CTFE
2217
+ }
2218
+ ---
2219
+ )
2220
+
2221
+ $(P CTFE is subject to the following restrictions:)
2222
+
2188
2223
$(OL
2189
2224
$(LI The function source code must be available to the compiler. Functions
2190
2225
which exist in the source code only as $(D_KEYWORD extern) declarations
@@ -2277,39 +2312,6 @@ static assert(countTen(12) == 12); // invalid, modifies y.
2277
2312
is used.
2278
2313
)
2279
2314
2280
-
2281
- $(P In order to be executed in CTFE, the function
2282
- must appear in a context where it must be so executed, for
2283
- example:)
2284
-
2285
- $(UL
2286
- $(LI initialization of a static variable or a manifest constant)
2287
- $(LI dimension of a static array)
2288
- $(LI argument for a template value parameter)
2289
- )
2290
-
2291
- $(SPEC_RUNNABLE_EXAMPLE_COMPILE
2292
- ---
2293
- template eval( A... )
2294
- {
2295
- const typeof(A[0]) eval = A[0];
2296
- }
2297
-
2298
- int square(int i)
2299
- {
2300
- return i * i;
2301
- }
2302
-
2303
- void foo()
2304
- {
2305
- static j = square(3); // compile time
2306
- writeln(j);
2307
- writeln(square(4)); // run time
2308
- writeln(eval!(square(5))); // compile time
2309
- }
2310
- ---
2311
- )
2312
-
2313
2315
$(P Executing functions via CTFE can take considerably
2314
2316
longer than executing it at run time.
2315
2317
If the function goes into an infinite loop, it will hang at
0 commit comments