C/C++ Arena

Step 1 of 6

Strategies as closures

The classic Strategy pattern swaps an algorithm at runtime. The textbook version uses an abstract base class and a subclass per strategy. When a strategy is a single function, modern C++ just uses std::function, and a function that returns a lambda builds configured strategies:

std::function<long(long)> percent_off(int pct) {
    return [pct](long cents) { return cents - cents * pct / 100; };
}

The lambda captures pct, so each returned strategy remembers its own settings. That's a closure.

Your turn: write the strategy factories percent_off(pct) and flat_off(amount) (never below 0), and Cart::total(), which sums the prices and applies the cart's discount strategy once to the sum.

Next: A factory registry