Expression Templates
Explore how expression templates represent computations at compile time to optimize C++ vector operations. Learn to replace multiple temporary objects with lazy evaluation that builds expression trees. Understand operator overloading to return proxy objects and trigger final evaluation only during assignment, improving performance and resource management.
We'll cover the following...
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 its length (lines 16–18).
- Has