Expression Templates
Learn about expression templates, their advantages, and their disadvantages.
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 support for index-based reading (lines 21–23).
- Has support for index-based writing (lines 25–27).
Take a look at the code below. We’ll provide a more detailed explanation after the coding playground.
Get hands-on with 1400+ tech skills courses.