Basic expression templates for element-wise algebra

suggest change

Expression templates represent an expression as a lightweight tree of objects and postpone its evaluation. Numeric libraries use this technique to combine several element-wise operations into one loop and avoid allocating intermediate containers.

Consider this expression:

Vector result = a + b * c;

An eager implementation first computes b * c into a temporary vector and then adds that temporary to a. An expression-template implementation instead builds an object representing this tree:

        add
       /   \
      a   multiply
          /      \
         b        c

Assigning the expression to result evaluates each element directly:

result[i] = a[i] + b[i] * c[i];

This fuses the operations into one pass and avoids an intermediate vector. Whether that improves performance depends on the expression, compiler, data size, memory access pattern, and target hardware, so measure representative workloads.

A small implementation

The following example shows the core idea. It omits production concerns such as allocator support, concepts, diagnostics, and specialized kernels. The transparent std::plus<> and std::multiplies<> function objects require C++14.

#include <cassert>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <utility>
#include <vector>

template<class E>
class Expression {
public:
    const E& derived() const { return static_cast<const E&>(*this); }
    std::size_t size() const { return derived().size(); }
    auto operator[](std::size_t i) const { return derived()[i]; }
};

template<class T>
class Vector : public Expression<Vector<T>> {
public:
    explicit Vector(std::size_t size) : values_(size) {}
    Vector(std::initializer_list<T> values) : values_(values) {}

    template<class E>
    Vector(const Expression<E>& expression) : values_(expression.size()) {
        const E& e = expression.derived();
        for (std::size_t i = 0; i < values_.size(); ++i) {
            values_[i] = e[i];
        }
    }

    std::size_t size() const { return values_.size(); }
    const T& operator[](std::size_t i) const { return values_[i]; }
    T& operator[](std::size_t i) { return values_[i]; }

private:
    std::vector<T> values_;
};

template<class Operation, class Left, class Right>
class BinaryExpression : public Expression<BinaryExpression<Operation, Left, Right>> {
public:
    BinaryExpression(const Left& left, const Right& right, Operation operation = {})
        : left_(left), right_(right), operation_(std::move(operation)) {
        assert(left_.size() == right_.size());
    }

    std::size_t size() const { return left_.size(); }
    auto operator[](std::size_t i) const {
        return operation_(left_[i], right_[i]);
    }

private:
    const Left& left_;
    const Right& right_;
    Operation operation_;
};

template<class Left, class Right>
auto operator+(const Expression<Left>& left, const Expression<Right>& right) {
    return BinaryExpression<std::plus<>, Left, Right>{
        left.derived(), right.derived()
    };
}

template<class Left, class Right>
auto operator*(const Expression<Left>& left, const Expression<Right>& right) {
    return BinaryExpression<std::multiplies<>, Left, Right>{
        left.derived(), right.derived()
    };
}

int main() {
    Vector<int> a{1, 2, 3};
    Vector<int> b{4, 5, 6};
    Vector<int> c{7, 8, 9};
    Vector<int> result = a + b * c;
}

Expression uses the curiously recurring template pattern to expose a common interface without virtual dispatch. BinaryExpression stores references to its operands and applies its operation only when an element is requested. Constructing result walks the expression once and stores the final values.

Lifetime and auto pitfalls

Expression objects often contain references. Storing one can therefore leave dangling references if an operand is a temporary:

auto expression = a + b * c; // Dangles: b * c is a temporary stored by reference.

auto also preserves the lazy expression rather than materializing a Vector. In this implementation the product is a temporary, so the auto variable dangles as soon as the initializer finishes, even while a, b, and c are still alive. Reusing a still-valid expression can also repeat the computation. Convert it to the concrete result type when a stored value is required:

Vector<int> result = a + b * c;

Real libraries address lifetimes by choosing carefully whether each node stores an operand by reference or by value. They may also use SIMD instructions, loop fusion, specialized kernels, and rules that decide when a temporary is cheaper than repeated evaluation.

Limits

Expression templates add complex types and can increase compile times and diagnostic size. Fusion is not always profitable, particularly when an intermediate value is reused or when a specialized matrix operation outperforms an element-wise loop. Their strongest use case is a library interface where the implementation can hide that complexity from callers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents