Expression Templates
Learn the runtime lazy evaluation process for compile-time computations.
We'll cover the following...
Expression templates are a metaprogramming technique that enables lazy evaluation of a computation at compile-time. This helps to avoid inefficient operations that occur at runtime. However, this does not come for free, as expression templates require more code and can be cumbersome to read or understand. They are often used in the implementation of linear algebra libraries.
Problem solved by expression templates
Before seeing how expression templates are implemented, let’s look at what problem they solve. For this, let’s suppose we want to do some operations with matrixes, for which we implemented the basic operations, addition, subtraction, and multiplication (either of two matrixes or of a scalar and a matrix). We can have the following expressions:
auto r1 = m1 + m2;auto r2 = m1 + m2 + m3;auto r3 = m1 * m2 + m3 * m4;auto r4 = m1 + 5 * m2;
In this snippet, m1
, m2
, m3
, and m4
are matrixes; similarly, r1
, r2
, r3
, and r4
are matrixes that result from performing the operations on the right side. The first operation doesn’t pose any problems: m1
and m2
are added, and the result is assigned to r1
. However, the second operation is different because there are three matrixes that are added. That means m1
and m2
are added first and a temporary is created, which is then added to m3
and the result assigned to r2
.
For the third operation, there are two temporaries: one for the result of multiplying m1
and m2
and one for the result of multiplying m3
and m4
; these two are then added, and the result is assigned to r3
. Finally, the last operation is similar to the second, meaning that a temporary object results from the multiplication between the scalar 5
and the matrix ...