ProblemsTemplatesVariadic sum (fold expression)
IntermediateTemplates

Variadic sum (fold expression)

Context

Billing adds up fees: ints here, doubles there, both at once elsewhere. The code has a ladder of overloads sum2, sum3, sum4 (yes, literally named that). Accounting found a one-cent discrepancy and now you have an audit. One variadic template with a fold expression replaces the whole ladder.

Task

Implement sum(args...) — a variadic function template that adds any number of arguments of any addable, possibly mixed, types. Use a C++17 fold expression, not hand-rolled recursion.

Constraints

  • Must be a variadic function template (typename... Ts)
  • Must use a fold expression (... + args) — no recursive helper, no manual base case
  • Must work for one or many arguments and for mixed arithmetic types
  • The result type should follow from + on the arguments (e.g. mixing int and double yields double)

Before you code

  • What does the fold expression (... + args) expand to for three arguments?
  • How does a fold expression remove the need for a recursive base case?
  • Why might the return type need auto / a common type rather than a fixed type?

Tests

  • #1Sums integers
  • #2Sums and mixes floating point

Hints

Hint 1

The whole body is one return: return (... + args); — a unary left fold over operator+.

Editorvariadic-sum.cpp
Results

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