Expression Templates
   HOME

TheInfoList



OR:

Expression templates are a
C++ C++ (, pronounced "C plus plus" and sometimes abbreviated as CPP or CXX) is a high-level, general-purpose programming language created by Danish computer scientist Bjarne Stroustrup. First released in 1985 as an extension of the C programmin ...
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these te ...
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 Loop fission (or loop distribution) is a compiler optimization in which a loop is broken into multiple loops over the same index range with each taking only a part of the original loop's body. The goal is to break down a large loop body into smalle ...
. 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 Linear algebra is the branch of mathematics concerning linear equations such as :a_1x_1+\cdots +a_nx_n=b, linear maps such as :(x_1, \ldots, x_n) \mapsto a_1x_1+\cdots +a_nx_n, and their representations in vector spaces and through matrix (mathemat ...
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 vector class Vec : public std::array ; /// @brief sum 'u' and 'v' into a new instance of Vec Vec 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 Return may refer to: In business, economics, and finance * Return on investment (ROI), the financial gain after an expense. * Rate of return, the financial term for the profit or loss derived from an investment * Tax return, a blank document or ...
this will allocate memory at least twice and require two loops.
Delayed evaluation In computer programming, a thunk is a subroutine used to inject a calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subro ...
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. 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 curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X derives from a class template instantiation using X itself as a template argument. More generally it is known as F-bound polymorphism, and it is a ...
. 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 In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
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 In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, in the C family of languages differs from similar constructs ...
reference A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
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 VecSum operator+(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 const& expr) with its template argument E being this type (meaning VecSum, Vec>). Inside this constructor, the loop body elems = expr is effectively expanded (following the recursive definitions of operator+ and operator[]on this type) to elems = a.elems + b.elems + c.elems 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 Matrix (: matrices or matrixes) or MATRIX may refer to: Science and mathematics * Matrix (mathematics), a rectangular array of numbers, symbols or expressions * Matrix (logic), part of a formula in prenex normal form * Matrix (biology), the ...
of numbers. Among libraries employing expression template are
Dlib Dlib is a general purpose cross-platform software library written in the programming language C++. Its design is heavily influenced by ideas from design by contract and component-based software engineering. Thus it is, first and foremost, a set o ...
,
Armadillo Armadillos () are New World placental mammals in the order (biology), order Cingulata. They form part of the superorder Xenarthra, along with the anteaters and sloths. 21 extant species of armadillo have been described, some of which are dis ...
, Blaze, Blitz++,
Boost Boost, boosted or boosting may refer to: Science, technology and mathematics * Boost, positive manifold pressure in turbocharged engines * Boost (C++ libraries), a set of free peer-reviewed portable C++ libraries * Boost (material), a material b ...
uBLAS,
Eigen Eigen may refer to: People with the given name *, Japanese sport shooter *, Japanese professional wrestler * Frauke Eigen (born 1969) German photographer, photojournalist and artist * Manfred Eigen (1927–2019), German biophysicist * Michael Ei ...
, POOMA, Stan Math Library, and xtensor. Expression templates can also accelerate C++
automatic differentiation In mathematics and computer algebra, automatic differentiation (auto-differentiation, autodiff, or AD), also called algorithmic differentiation, computational differentiation, and differentiation arithmetic Hend Dawood and Nefertiti Megahed (2023) ...
implementations, as demonstrated in the Adept library. Outside of vector math, the
Spirit parser framework The Spirit Parser Framework is an object oriented recursive descent parser generator framework implemented using template metaprogramming techniques. Expression templates allow users to approximate the syntax of extended Backus–Naur form (EBNF) c ...
uses expression templates to represent
formal grammar A formal grammar is a set of Terminal and nonterminal symbols, symbols and the Production (computer science), production rules for rewriting some of them into every possible string of a formal language over an Alphabet (formal languages), alphabe ...
s and compile these into parsers.


See also

*


References

{{reflist, 30em C++ Compiler optimizations Metaprogramming