The output of these templates can include compile-time constants, data structures, and complete functions.
[1][2] Some other languages support similar, if not more powerful, compile-time facilities (such as Lisp macros), but those are outside the scope of this article.
Textual macros are notably more independent of the syntax of the language being manipulated, as they merely change the in-memory text of the source code right before compilation.
As another, more significant, example of compile-time loop unrolling, template metaprogramming can be used to create length-n vector classes (where n is known at compile time).
The benefit over a more traditional length-n vector is that the loops can be unrolled, resulting in very optimized code.
[5] Another similar use is the "Barton–Nackman trick", sometimes referred to as "restricted template expansion", where common functionality can be placed in a base class that is used not as a contract but as a necessary component to enforce conformant behaviour while minimising code redundancy.
The following listing shows an example of creating a very simple table by using recursive structs and variadic templates.
Since C++17 this can be more readably written as: To show a more sophisticated example the code in the following listing has been extended to have a helper for value calculation (in preparation for more complicated computations), a table specific offset and a template argument for the type of the table values (e.g. uint8_t, uint16_t, ...).
Here is an example of the famous Fizz buzz problem solved with Template Meta Programming.
Compile-time versus execution-time tradeoffs get visible if a great deal of template metaprogramming is used.