CTFE is a mechanism which allows the compiler to execute functions at compile time. There is no special set of the D language necessary to use this feature - whenever a function just depends on compile time known values the D compiler might decide to interpret it during compilation.
// result will be calculated at compile // time. Check the machine code, it won't // contain a function call! static val = sqrt(50);
instruct the compiler to use CTFE whenever possible.
The great thing about this technique is that
functions don't need to be rewritten to use
it, and the same code can perfectly be shared:
int n = doSomeRuntimeStuff(); // same function as above but this // time it is just called the classical // run-time way. auto val = sqrt(n);
One prominent example in D is the std.regex
library. It provides the
ctRegex type which uses
string mixins and CTFE to generate a highly optimized
regular expression automaton that is generated during
compilation. The same code base is re-used for
the run-time version
regex that allows regular
expressions only available at run-time to be compiled.
auto ctr = ctRegex!(`^.*/([^/]+)/?$`); auto tr = regex(`^.*/([^/]+)/?$`); // ctr and tr can be used interchangely // but ctr will be faster!
Not all language features are available during CTFE but the supported feature set is increased with every release of the compiler.