ProblemsModern C++The comma conveyor
AdvancedModern C++

The comma conveyor

Context

The comma is an overloadable operator in C++, and overloading it lets functors chain: each comma takes the number on the left and the functor on the right, applies, and passes the result on. Production code avoids this — but understanding when the overload is picked over the built-in comma teaches how operator resolution treats the strangest member of the family.

Task

Make (4, a, b, c) compute c(b(a(4))): functor objects Mult_3, Add_5, Minus_1 are applied left to right through an overloaded comma operator. A legal, if exotic, corner of operator overloading.

Constraints

  • (4, a, b, c) with Mult_3 a, Add_5 b, Minus_1 c equals ((4 * 3) + 5) - 1 == 16
  • Each functor is reusable and stateless
  • The chain works for any length and order of these functors
  • operator,(int, <functor>) does the work — no macros

Before you code

  • Why does the built-in comma not apply here once an overload exists?
  • What does the overloaded comma lose that the built-in guarantees? (sequencing, until C++17 rules)
  • Why is this an anti-pattern outside exams?

Tests

  • #1Functor chains
  • #2Order matters

Hints

Hint 1

One template operator,(int, const F&) covers all three functors: it applies f to the value and returns int — ready for the next comma.

Hint 2

The comma associates left to right, so the chain folds itself: ((4, a), b), c.

Editorcomma-pipeline.cpp
Results

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