ArticleslgStudy

science

Expression templates

Expression templates 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 Expression templates rather than just read about it. In short: Expression templates are a C++ template metaprogramming technique that builds structures representing a computation at compile time, where expressions are evaluated only as needed to produce efficient code for the entire computation. Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion.

Key takeaways

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

Reference excerpt

Expression templates are a C++ template metaprogramming technique that builds structures representing a computation at compile time, where expressions are evaluated only as needed to produce efficient code for the entire computation. Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion. Expression templates were invented independently by Todd Veldhuizen and David Vandevoorde; it was Veldhuizen who gave them their name. They are a popular technique for the implementation of linear algebra software.

Motivation and example Consider a library representing vectors and operations on them. One common mathematical operation is to add two vectors u and v, element-wise, to produce a new vector. The obvious C++ implementation of this operation would be an overloaded operator+ that returns a new vector object:

Users of this class can now write Vec3 x = a + b; where a and b are both instances of Vec3. A problem with this approach is that more complicated expressions such as Vec3 x = a + b + c are implemented inefficiently. The implementation first produces a temporary Vec3 to hold a + b, then produces another Vec3 with the elements of c added in. Even with return value optimization this will allocate memory at least twice and require two loops. Delayed evaluation solves this problem, and can be implemented in C++ by letting operator+ return an object of an auxiliary type, say Vec3Sum, that represents the unevaluated sum of two Vec3s, or a vector with a Vec3Sum, etc. Larger expressions then effectively build expression trees that are evaluated only when assigned to an actual Vec3 variable. But this requires traversing such trees to do the evaluation, which is in itself costly. Expression templates implement delayed evaluation using expression trees that only exist at compile time. Each assignment to a Vec3, such as Vec3 x = a + b + c, generates a new Vec3 constructor if needed by template instantiation. This constructor operates on three Vec3s; it allocates the necessary memory and then performs the computation. Thus only one memory allocation is performed.

Example implementation of expression templates An example implementation of expression templates looks like the following. A base class Vec3Expression represents any vector-valued expression. It is templated on the actual expression type E to be implemented, per the curiously recurring template pattern. The existence of a base class like VecExpression is not strictly necessary for expression templates to work. It will merely serve as a function argument type to distinguish the expressions from other types (note the definition of a Vec3 constructor and operator+ below).

The Boolean is_leaf is there to tag VecExpressions that are "leafs", i.e. that actually contain data. The Vec3 class is a leaf that stores the coordinates of a fully evaluated vector expression, and becomes a subclass of VecExpression.

The sum of two Vec3s is represented by a new type, VecSum, that is templated on the types of the left- and right-hand sides of the sum so that it can be applied to arbitrary pairs of Vec3 expressions. An overloaded operator+ serves as syntactic sugar for the VecSum constructor. A subtlety intervenes in this case: in order to reference the original data when summing two VecExpressions, VecSum needs to store a const reference to each VecExpression if it is a leaf, otherwise it is a temporary object that needs to be copied to be properly saved.

With the above definitions, the expression a + b + c is of type

so Vec3 x = a + b + c invokes the templated Vec3 constructor Vec3(VecExpression<E> const& expr) with its template argument E being this type (meaning Vec3Sum<Vec3Sum<Vec3, Vec3>, Vec3>). Inside this constructor, the loop body

is effectively expanded (following the recursive definitions of operator+ and operator[]on this type) to

with no temporary Vec objects needed and only one pass through each memory block.

Basic usage The following demonstrates basic usage of the above:

Applications Expression templates have been found especially useful by the authors of libraries for linear algebra, that is, for dealing with vectors and matrices of numbers. Among libraries employing expression template are Dlib, Armadillo, Blaze, Blitz++, Boost uBLAS, Eigen, POOMA, Stan Math Library, and xtensor. Expression templates can also accelerate C++ automatic differentiation implementations, as demonstrated in the Adept library. Outside of vector math, the Spirit parser framework uses expression templates to represent formal grammars and compile these into parsers.

See also Optimizing compiler – Compiler that optimizes generated code

References Pflaum C., Expression templates for partial differential equations. Comput Visual Sci 4, 1–8 (2001). https://doi.org/10.1007/s007910100051 Pflaum C, Rahimi Z., Automatic parallelisation of staggered grid codes with expression templates. International Journal of Computational Science and Engineering, Volume 4, Issue 4, Pages 306 – 313, https://doi.org/10.1504/IJCSE.2009.029166

Worked examples

Example 1 — a first encounter with Expression templates

Start with the simplest possible case. Write down what Expression templates 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 Expression templates 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 Expression templates 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 Expression templates

In research
Expression templates 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 Expression templates 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
Expression templates is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Compiler optimizations, Metaprogramming, so understanding it makes those chapters shorter.
In everyday life
Look for Expression templates 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.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Expression templates” →

How to study Expression templates in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Expression templates 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 Expression templates out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Expression templates in simple terms?

Expression templates are a C++ template metaprogramming technique that builds structures representing a computation at compile time, where expressions are evaluated only as needed to produce efficient code for the entire computation. Expression templates thus allow programmers to bypass the normal…

Why does Expression templates 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 Expression templates?

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 Expression templates.

Tags

  • C++
  • Compiler optimizations
  • Metaprogramming

Keep exploring