Metaprogramming

Metaprogramming in C++ (a.k.a template metaprogramming) uses the fact that templates are instantiated at compile time an not at run time. This makes it possible to create a template which calculates a value at return time, a value which can then be used as a constant in the rest of the program.

Say that we create a template struct which only contains a single value

the definition of the value is recursive and refers to the calculation of the factorial of a value one-less than the requested value. However, this will not in itself compile since the compiler will get stuck in an infinite loop trying to calculate the factorial of one-less than the value eventually crashing the compilation. To stop the compiler it must be given a stopping condition, a special case where we explicitly tell the compiler what the value of the factorial is. This is done like this:

And to calculate the value of the factorial, you simply need to create an instance of the template:

 

See also the C++ book: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming

Facebookgoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *