HOME

TheInfoList



OR:

Expression templates are a
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
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 In computer science, 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 l ...
. 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 matrices. ...
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: class 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 In C++ computer programming, copy elision refers to a compiler optimization technique that eliminates unnecessary copying of objects. The C++ language standard generally allows implementations to perform any optimization, provided the resulting pr ...
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 a custom 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 f ...
. 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 Vec class still 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. 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 most commonly refers to: * ''The Matrix'' (franchise), an American media franchise ** ''The Matrix'', a 1999 science-fiction action film ** "The Matrix", a fictional setting, a virtual reality environment, within ''The Matrix'' (franchis ...
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 ...
,
Armadillo Armadillos (meaning "little armored ones" in Spanish) are New World placental mammals in the order Cingulata. The Chlamyphoridae and Dasypodidae are the only surviving families in the order, which is part of the superorder Xenarthra, along wi ...
, Blaze,
Blitz++ Blitz++ is a high-performance vector mathematics library written in C++. This library is intended for use in scientific applications that might otherwise be implemented with Fortran or MATLAB MATLAB (an abbreviation of "MATrix LABoratory") ...
, Boost uBLAS,
Eigen Eigen may refer to: * Eigen (C++ library), computer programming library for matrix and linear algebra operations * Eigen Technologies, the Document AI software company * Eigen, Schwyz, settlement in the municipality of Alpthal in the canton of Schw ...
, POOMA, Stan Math Library, and xtensor. Expression templates can also accelerate C++
automatic differentiation In mathematics and computer algebra, automatic differentiation (AD), also called algorithmic differentiation, computational differentiation, auto-differentiation, or simply autodiff, is a set of techniques to evaluate the derivative of a function s ...
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) ...
uses expression templates to represent
formal grammar In formal language theory, a grammar (when the context is not given, often called a formal grammar for clarity) describes how to form strings from a language's alphabet that are valid according to the language's syntax. A grammar does not describe ...
s and compile these into parsers.


See also

*


References

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