Expression templates explained

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.[1] 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;[2] [3] 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 and, 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:

/// @brief class representing a mathematical 3D vectorclass Vec : public std::array ;

/// @brief sum 'u' and 'v' into a new instance of VecVec operator+(Vec const &u, Vec const &v)

Users of this class can now write Vec x = a + b; where a and b are both instances of Vec.

A problem with this approach is that more complicated expressions such as Vec x = a + b + c are implemented inefficiently. The implementation first produces a temporary Vec to hold a + b, then produces another Vec 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 VecSum, that represents the unevaluated sum of two Vecs, or a vector with a VecSum, etc. Larger expressions then effectively build expression trees that are evaluated only when assigned to an actual Vec variable. But this requires traversing such trees to do the evaluation, which is in itself costly.[4]

Expression templates implement delayed evaluation using expression trees that only exist at compile time. Each assignment to a Vec, such as Vec x = a + b + c, generates a new Vec constructor if needed by template instantiation. This constructor operates on three Vec; 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 VecExpression 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 Vec constructor and operator+ below).

template class VecExpression ;

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

class Vec : public VecExpression ;

The sum of two Vecs 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 Vec 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.

template class VecSum : public VecExpression > ; template VecSumoperator+(VecExpression const& u, VecExpression const& v)

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

VecSum, Vec>

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

elems[i] = expr[i];

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

elems[i] = a.elems[i] + b.elems[i] + c.elems[i];

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

Basic Usage :

int main

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,[5] Blitz++,[6] Boost uBLAS,[7] Eigen,[8] POOMA,[9] Stan Math Library,[10] and xtensor.[11] Expression templates can also accelerate C++ automatic differentiation implementations,[12] 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.

Notes and References

  1. Kiminori . Matsuzaki . Kento . Emoto . Implementing fusion-equipped parallel skeletons by expression templates . Proc. Int'l Symp. on Implementation and Application of Functional Languages . 2009 . 72–89.
  2. Book: Vandevoorde . David . Josuttis . Nicolai . C++ Templates: The Complete Guide . . 2002 . 0-201-73484-2.
  3. Veldhuizen . Todd . Expression Templates . C++ Report . 7 . 5 . 1995 . 26–31 . https://web.archive.org/web/20050210090012/http://osl.iu.edu/~tveldhui/papers/Expression-Templates/exprtmpl.html . 10 February 2005.
  4. Book: C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond . David . Abrahams . Aleksey . Gurtovoy . Pearson Education . 2004 . 9780321623911 .
  5. https://bitbucket.org/blaze-lib/blaze Bitbucket
  6. Web site: Blitz++ User's Guide. December 12, 2015.
  7. Web site: Boost Basic Linear Algebra Library. October 25, 2015.
  8. Eigen: A C++ linear algebra library . Gaël . Guennebaud . 2013 . Eurographics/CGLibs .
  9. Todd . Veldhuizen . Just when you thought your little language was safe: "Expression Templates" in Java . 2000 . Int'l Symp. Generative and Component-Based Software Engineering . 10.1.1.22.6984.
  10. Web site: Stan documentation . April 27, 2016.
  11. Web site: Multi-dimensional arrays with broadcasting and lazy computing . September 18, 2017.
  12. Hogan. Robin J.. Fast reverse-mode automatic differentiation using expression templates in C++. ACM Trans. Math. Softw.. 2014. 40. 4. 26:1–26:16. 10.1145/2560359. 9047237.