encyclopegia.org

Expression templates

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.[src] Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion.[src] Expression templates were invented independently by Todd Veldhuizen and David Vandevoorde; it was Veldhuizen who gave them their name.[src] They are a popular technique for the implementation of linear algebra software.[src]

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.[src] Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion.[src] Expression templates were invented independently by Todd Veldhuizen and David Vandevoorde; it was Veldhuizen who gave them their name.[src] They are a popular technique for the implementation of linear algebra software.[src] ==Motivation and example== Consider a library representing vectors and operations on them.[src] One common mathematical operation is to add two vectors and , element-wise, to produce a new vector.[src] The obvious C++ implementation of this operation would be an overloaded operator+ that returns a new vector object: import std; using std::array; /// @brief class representing a mathematical 3D vector class Vec3 : public array { public: Vec3(): array () {} }; /// @brief sum 'u' and 'v' into a new instance of Vec3 Vec3 operator+(Vec3 const& u, Vec3 const& v) { Vec3 sum; for (size_t i = 0; i Users of this class can now write Vec3 x = a + b; where a and b are both instances of Vec3 .[src] A problem with this approach is that more complicated expressions such as Vec3 x = a + b + c are implemented inefficiently.[src] The implementation first produces a temporary Vec3 to hold a + b , then produces another Vec3 with the elements of c added in.[src] Even with return value optimization this will allocate memory at least twice and require two loops.[src] Delayed evaluation solves this problem, and can be implemented in C++ by letting operator+ return an object of an auxiliary type, say Vec3Sum , that represents the unevaluated sum of two Vec3 s, or a vector with a Vec3Sum , etc.[src] Larger expressions then effectively build expression trees that are evaluated only when assigned to an actual Vec3 variable.[src] But this requires traversing such trees to do the evaluation, which is in itself costly.[src] Expression templates implement delayed evaluation using expression trees that only exist at compile time.[src] Each assignment to a Vec3 , such as Vec3 x = a + b + c , generates a new Vec3 constructor if needed by template instantiation.[src] This constructor operates on three Vec3 s; it allocates the necessary memory and then performs the computation.[src] Thus only one memory allocation is performed.[src] ===Example implementation of expression templates=== An example implementation of expression templates looks like the following.[src] A base class Vec3Expression represents any vector-valued expression.[src] It is templated on the actual expression type E to be implemented, per the curiously recurring template pattern.[src] The existence of a base class like VecExpression is not strictly necessary for expression templates to work.[src] It will merely serve as a function argument type to distinguish the expressions from other types (note the definition of a Vec3 constructor and operator+ below).[src] import std; template class VecExpression { public: static constexpr bool IS_LEAF = false; nodiscard double operator[](size_t i) const { // Delegation to the actual expression type.[src] This avoids dynamic polymorphism (a.k.a.[src] virtual functions in C++) return static_cast (*this)[i]; } nodiscard size_t size() const { return static_cast (*this).size(); } }; The Boolean is_leaf is there to tag VecExpression s that are "leafs", i.e.[src] that actually contain data.[src] The Vec3 class is a leaf that stores the coordinates of a fully evaluated vector expression, and becomes a subclass of VecExpression .[src] import std; using std::array; using std::initializer_list; class Vec3 : public VecExpression { private: array elems; public: static constexpr bool IS_LEAF = true; nodiscard double operator[](size_t i) const noexcept { return elems[i]; } double& operator[](size_t i) noexcept { return elems[i]; } nodiscard size_t size() const noexcept { return elems.size(); } // construct Vec using initializer list Vec3(initializer_list init) { std::ranges::copy(init, elems.begin()); } // A Vec can be constructed from any VecExpression, forcing its evaluation.[src] template Vec3(VecExpression const& expr) { for (size_t i = 0; i != expr.size(); ++i) { elems[i] = expr[i]; } } }; The sum of two Vec3 s 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 Vec3 expressions.[src] An overloaded operator+ serves as syntactic sugar for the VecSum constructor.[src] A subtlety intervenes in this case: in order to reference the original data when summing two VecExpression s, 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.[src] import std; using std::conditional; template class Vec3Sum : public VecExpression > { private: // cref if leaf, copy otherwise typename conditional ::type u; typename conditional ::type v; public: static constexpr bool IS_LEAF = false; Vec3Sum(E1 const& u, E2 const& v): u{u}, v{v} { assert(u.size() == v.size()); } nodiscard double operator[](size_t i) const noexcept { return u[i] + v[i]; } nodiscard size_t size() const noexcept { return v.size(); } }; template Vec3Sum operator+(VecExpression const& u, VecExpression const& v) { return Vec3Sum (*static_cast (&u), *static_cast (&v)); } With the above definitions, the expression a + b + c is of type Vec3Sum , Vec3> so Vec3 x = a + b + c invokes the templated Vec3 constructor Vec3(VecExpression const& expr) with its template argument E being this type (meaning Vec3Sum , Vec3> ).[src] 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.[src] ===Basic usage=== The following demonstrates basic usage of the above: import std; int main() { Vec3 v0{23.4, 12.5, 144.56}; Vec3 v1{67.12, 34.8, 90.34}; Vec3 v2{34.90, 111.9, 45.12}; // Following assignment will call the ctor of Vec3 which accept type of // `VecExpression const&`.[src] Then expand the loop body to // a.elems[i] + b.elems[i] + c.elems[i] Vec3 sumOfVecType = v0 + v1 + v2; for (size_t i = 0; i , Vec3> // and this chaining of operations can go on.[src] } ==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.[src] Among libraries employing expression template are Dlib, Armadillo, Blaze, Blitz++, Boost uBLAS, Eigen, POOMA, Stan Math Library, and xtensor.[src] Expression templates can also accelerate C++ automatic differentiation implementations, as demonstrated in the Adept library.[src] Outside of vector math, the Spirit parser framework uses expression templates to represent formal grammars and compile these into parsers.[src] ==See also== ==References== Pflaum C., Expression templates for partial differential equations.[src] Comput Visual Sci 4, 1–8 (2001).[src] https://doi.org/10.1007/s007910100051 Pflaum C, Rahimi Z., Automatic parallelisation of staggered grid codes with expression templates.[src] International Journal of Computational Science and Engineering, Volume 4, Issue 4, Pages 306 – 313, https://doi.org/10.1504/IJCSE.2009.029166[src]

47 sentences · 47 cited inline · 0 references stored

References

No reference rows published for this article.

Cite this article

MLA

"Expression templates." encyclopegia.org, 2026, https://encyclopegia.org/wiki/expression-templates. Accessed 25 November 2026.

Chicago

"Expression templates." encyclopegia.org. Accessed November 25, 2026. https://encyclopegia.org/wiki/expression-templates.

APA

encyclopegia.org. (2026). Expression templates. Retrieved November 25, 2026, from https://encyclopegia.org/wiki/expression-templates

Accessed November 25, 2026 · CC BY-SA 4.0 · citation page · JSON

CC BY-SA 4.0 · share-alike · https://en.wikipedia.org/w/index.php?oldid=1378180028 · 0.5 · snapshot enwiki-001378180028

Cite · JSON · Search

Related services and records

Services

  • Estate — measured countries, lanes and facts
  • Intel — live corroborated events
  • Legal — statutes, cases and citations
  • Encyclopedia — articles with inline sources
  • Space — launches, satellites and orbits
  • Search — federated search and reports
  • Pass — passport account and SSO
  • Corpora — read-only corpus origins
  • e01 — self-hosted corpora and tools

Text and metadata only; each target carries its own sources. Missing data is published as no-data, never estimated.