Compile-time function execution: Difference between revisions

Content deleted Content added
Improved many parts, cleaned up, splitted a paragraph, removed a redundant example, added a variant of the example
Removed execessive references to the D language
Line 1:
'''Compile time function execution''' is the ability of a [[compiler]], that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state (is a [[pure function]]).
 
Even if the value of only some of the arguments are known, the compiler may still be able to perform some level of compile time function execution ([[partial evaluation]]), possibly producing more optimized code than if no arguments were known (currently there are no plans to implement such partial evaluation in any D compiler).
 
==Example==
Line 24:
int y = Factorial<4>::value; // == 24
}
</source>
 
D templates can be used for the same purpose:
 
<source lang="D">
template Factorial(int N) {
static if (N == 0)
const int Factorial = 1;
else
const int Factorial = N * Factorial!(N - 1);
}
 
const int y = Factorial!(0); // == 1
const int x = Factorial!(4); // == 24
</source>