Expression templates
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.
Before seeing how expression templates are implemented, let’s understand what is the problem they solve. For this, let’s suppose we want to do some operations with matrices, for which we implemented the basic operations, addition, subtraction, and multiplication (either of two matrices 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 matrices; similarly, r1
, r2
, r3
, and r4
are matrices that result from performing the...