ProblemsModern C++Numbers through a pipe
IntermediateModern C++

Numbers through a pipe

Context

Reading nested calls inside out — multiply(div(minus(10, 2), 4), 2) — is painful. A pipeline reads left to right, in the order things actually happen. The whole trick is one overloaded operator and tiny objects that carry an operation and its argument.

Task

Make this expression work: 10 | minus(2) | div(4) | multiply(2) == 4. Each helper returns a small operation object; operator| applies it to the number on the left. This is the same pattern as ranges pipelines in C++20.

Constraints

  • plus(x), minus(x), multiply(x), div(x) each return an operation object
  • operator|(int, op) applies the operation and returns int — chains evaluate left to right
  • No global mutable state; the operation object carries everything it needs
  • Division is integer division

Before you code

  • Why does the chain evaluate left to right? (operator| associativity)
  • What minimal state must the operation object store?
  • Where does C++20 use exactly this pattern?

Tests

  • #1The sample chains
  • #2Left-to-right order matters
  • #3An operation object is reusable

Hints

Hint 1

The operation object needs two things: which operation and the right-hand argument. The left argument arrives later — in operator|.

Hint 2

A captureless lambda converts to a plain function pointer — handy for storing "which operation" without std::function.

Editorpipeline-operator.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.