Compile-time function execution: Difference between revisions

Content deleted Content added
No edit summary
m added syntax highlighting
Line 7:
This example code is in the [[D programming language]]:
 
<source lang="D">
int square(int x)
{
return x * x;
}
 
const int y = square(3); // y is set to 9 at compile time
</source>
 
===Example 2===
Line 18 ⟶ 20:
In [[C++]], [[template metaprogramming]] is often used to compute values at compile time, such as:
 
<source lang="CPP">
<pre>
template <int N>
struct Factorial
Line 38 ⟶ 40:
int y = Factorial<0>::value; // == 1
}
</presource>
 
With compile time function evaluation, the code used to generate the factorial would be exactly the same as what one would write for run time evaluation (example is in D):
 
<source lang="D">
<pre>
int factorial(int n)
{
Line 55 ⟶ 57:
static const int y = factorial(0); // == 0! == 1
}
</presource>
 
The use of static const tells the compiler that the initializer for the variables must be computed at compile time.