Expression Templates

In this lesson, we'll study expression templates in detail.

Expression Templates

Expression templates are “structures representing a computation at compile-time, which are evaluated only as needed to produce efficient code for the entire computation.”

Now we are at the center of lazy evaluation.

Lazy Evaluation

The story about lazy evaluation in C++ is quite short. That will change in C++20, with the ranges library from Eric Niebler. Lazy evaluation is the default in Haskell. Lazy evaluation means that an expression is only evaluated when needed.

This strategy has two benefits.

  • Lazy evaluation helps you to save time and memory.
  • You can define an algorithm on infinite data structures. Of course, you can only ask for a finite number of values at runtime.

Advantages:

  • Creates a domain-specific language (DSL)
  • Avoidance of temporary data structures

Disadvantages:

  • Longer compile-times
  • Advanced programming technique (template metaprogramming)

What problem do expression templates solve? Thanks to expression templates, we can get rid of superfluous temporary objects in expressions. What do we mean by superfluous temporary objects? To demonstrate that, let’s look at the implementation of the class MyVector below.

A First Naive Approach

MyVector is a simple wrapper for an std::vector<T>. The wrapper class has two constructors (line 12 and 15), we have a size function which returns its size (line 18 - 20), and the reading index operator (line 23 - 25) and writing index access (line 27 - 29).

Given below is the naive vector implementation:

Get hands-on with 1000+ tech skills courses.