Search⌘ K
AI Features

Expression Templates

Explore the concept of expression templates in C++ to understand how they build and evaluate computation trees lazily, avoiding the creation of superfluous temporary objects. This lesson helps you grasp both a naive and an optimized implementation, equipping you to write more efficient and cleaner vector operations in C++.

Overview

Expression templates are structures representing a computation at compile time, where expressions are evaluated only as needed to produce efficient code for the entire computation. Now, we’re at the center of lazy evaluation.

What problems 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? Let’s look at the following code, where we have implemented a MyVector class.

Naive approach

The simple wrapper MyVector wraps std::vector<T>. The wrapper:

  • Has two constructors (on lines 10 and 13).
  • Knows
...