ArticleslgStudy

science

Template metaprogramming

Template metaprogramming is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Template metaprogramming rather than just read about it. In short: Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data structures, and complete functions.

Key takeaways

  • Template metaprogramming belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Template metaprogramming to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Template metaprogramming from memory before moving on to harder problems.

Reference excerpt

Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time polymorphism. The technique is used by a number of languages, the best-known being C++, but also Curl, D, Nim, and XL. Template metaprogramming was, in a sense, discovered accidentally. Some other languages support similar, if not more powerful, compile-time facilities (such as Lisp's macros).

Components of template metaprogramming The use of templates as a metaprogramming technique requires two distinct operations: a template must be defined, and a defined template must be instantiated. The generic form of the generated source code is described in the template definition, and when the template is instantiated, the generic form in the template is used to generate a specific set of source code. Template metaprogramming is Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram. Templates are different from macros. A macro is a piece of code that executes at compile time and either performs textual manipulation of code to-be compiled (e.g. C++ macros) or manipulates the abstract syntax tree being produced by the compiler (e.g. Rust or Lisp macros). 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. Template metaprograms have no mutable variables— that is, no variable can change value once it has been initialized, therefore template metaprogramming can be seen as a form of functional programming. In fact many template implementations implement flow control only through recursion, as seen in the example below.

Using template metaprogramming Though the syntax of template metaprogramming is usually very different from the programming language it is used with, it has practical uses. Some common reasons to use templates are to implement generic programming (avoiding sections of code which are similar except for some minor variations) or to perform automatic compile-time optimization such as doing something once at compile time rather than every time the program is run — for instance, by having the compiler unroll loops to eliminate jumps and loop count decrements whenever the program is executed.

Compile-time class generation What exactly "programming at compile-time" means can be illustrated with an example of a factorial function, which in non-template C++ can be written using recursion as follows:

The code above will execute at run time to determine the factorial value of the literals 0 and 4. By using template metaprogramming and template specialization to provide the ending condition for the recursion, the factorials used in the program—ignoring any factorial not used—can be calculated at compile time by this code:

The code above calculates the factorial value of the literals 0 and 4 at compile time and uses the results as if they were precalculated constants. To be able to use templates in this manner, the compiler must know the value of its parameters at compile time, which has the natural precondition that Factorial<X>::value can only be used if X is known at compile time. In other words, X must be a constant literal or a constant expression. In C++11 and C++20, constexpr and consteval were introduced to let the compiler execute code. Using constexpr and consteval, one can use the usual recursive factorial definition with the non-templated syntax.

Compile-time code optimization

The factorial example above is one example of compile-time code optimization in that all factorials used by the program are pre-compiled and injected as numeric constants at compilation, saving both run-time overhead and memory footprint. It is, however, a relatively minor optimization. As another, more significant, example of compile-time loop unrolling, template metaprogramming can be used to create length- n {\displaystyle n} vector classes (where n {\displaystyle n} is known at compile time). The benefit over a more traditional length- n {\displaystyle n} vector is that the loops can be unrolled, resulting in very optimized code. As an example, consider the addition operator. A length- n {\displaystyle n} vector (where n {\displaystyle n} is represented by the non-type template parameter Length) addition might be written as

When the compiler instantiates the function template defined above, the following code may be produced:

The compiler's optimizer should be able to unroll the for loop because the template parameter Length is a constant at compile time. However, care must be taken as this may cause code bloat, since separate unrolled code will be generated for each n {\displaystyle n} (vector size) the template is instantiated with.

Static polymorphism Polymorphism is a common standard programming facility where derived objects can be used as instances of their base object but where the derived objects' methods will be invoked, as in this code

where all invocations of virtual methods will be those of the most-derived class. This dynamically polymorphic behaviour is (typically) obtained by the creation of virtual look-up tables for classes with virtual methods, tables that are traversed at run time to identify the method to be invoked. Thus, run-time polymorphism necessarily entails execution overhead (though on modern architectures the overhead is small). However, in many cases the polymorphic behaviour needed is invariant and can be determined at compile time. Then the Curiously Recurring Template Pattern (CRTP) can be used to achieve static polymorphism, which is an imitation of polymorphism in programming code but which is resolved at compile time and thus does away with run-time virtual-table lookups. For example:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Template metaprogramming

Start with the simplest possible case. Write down what Template metaprogramming claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Template metaprogramming before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Template metaprogramming ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Template metaprogramming

In research
Template metaprogramming appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Template metaprogramming in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Template metaprogramming is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Metaprogramming, so understanding it makes those chapters shorter.
In everyday life
Look for Template metaprogramming outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Template metaprogramming in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Template metaprogramming means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Template metaprogramming out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Template metaprogramming in simple terms?

Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data struc…

Why does Template metaprogramming matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Template metaprogramming?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Template metaprogramming.

Tags

  • C++
  • Metaprogramming

Keep exploring