Compile Time Function Execution - Example

Example

In earlier versions of C++, template metaprogramming is often used to compute values at compile time, such as:

template struct Factorial { enum { value = N * Factorial::value }; }; template <> struct Factorial<0> { enum { value = 1 }; }; // Factorial<4>::value == 24 // Factorial<0>::value == 1 void foo { int x = Factorial<0>::value; // == 1 int y = Factorial<4>::value; // == 24 }

Using compile time function evaluation, code used to compute the factorial would be exactly the same as what one would write for run time evaluation. Here's an example of CTFE in the D programming language:

int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } // computed at compile time const int y = factorial(0); // == 1 const int x = factorial(4); // == 24

This example specifies a valid D function called "factorial" which would typically be evaluated at run time. The use of const tells the compiler that the initializer for the variables must be computed at compile time. Note that the arguments to the function must be able to be resolved at compile time as well.

CTFE can be used to populate data structures at compile-time in a simple way (D version 2):

int genFactorials(int n) { auto result = new int; result = 1; foreach (i; 1 .. n) result = result * i; return result; } enum factorials = genFactorials(13); void main {} // 'factorials' contains at compile-time: // [1, 1, 2, 6, 24, 120, 720, 5_040, 40_320, 362_880, 3_628_800, // 39_916_800, 479_001_600]

In C++11 the equivalent technique is known as Generalized constant expressions.

Read more about this topic:  Compile Time Function Execution

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)