Expression templates

[1] Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion.

The Vec class is a leaf that stores the coordinates of a fully evaluated vector expression, and becomes a subclass of VecExpression.

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.

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 : 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.

[11] Expression templates can also accelerate C++ automatic differentiation implementations,[12] as demonstrated in the Adept library.