add section about CTFE

This commit is contained in:
Johannes Loher 2018-06-07 22:17:02 +02:00
parent 74257052c0
commit e972fd631e

View file

@ -1371,3 +1371,45 @@ assert(c == 5);
immutable runTimeString = q{int c =5;};
mixin(runTimeString); // compile error, runTimeString is not known at compile-time
```
### Compile Time Function Evaluation (CTFE)
In D, it is possible to execute functions at compile time. This is triggered on
the call site, i.e. whenever a function is called in a context where the result
needs to be known at compile time, the function will be evaluated at compile
time. Some of those contexts are:
* Template parameters
* Initialization of `static` variables
* Definition of `enum`s (i.e. compile time constants)
* `static assert`, `static foreach` and `static if`
* Template constraints
There are some limitations to what a function executed at compile time may do.
Essentially, the functions need to be *pure* in some sense, i.e. they may not
have side effects such as IO.
```D
import std.stdio : writeln;
auto sqrt(T)(T x) {
enum GoodEnough = 0.01;
import std.math : abs;
T z = x*x, old = 0;
int iter;
while (abs(z - old) > GoodEnough) {
old = z;
z -= ((z*z)-x) / (2*z);
}
return z;
}
void main() {
double n = 4.0;
writeln("The sqrt of runtime 4 = ",
sqrt(n));
static cn = sqrt(4.0); // calculated at compile time
writeln("The sqrt of compile time 4 = ",
cn);
}
```