ProblemsTemplatesjoinWith: variadic fold over a stream
AdvancedTemplates

joinWith: variadic fold over a stream

Context

The codebase has twelve overloads of makeLogLine: two args, three, four... The author stopped at seven because 'nobody will ever need more'. Somebody needed more. Instead of overload thirteen, write one variadic template: a fold expression joins anything.

Task

Implement joinWith(sep, args...) — join any number of streamable values of mixed types into one string with sep between them: joinWith("-", 2026, "jun", 10)"2026-jun-10". Use a variadic template with a C++17 fold expression — no recursion, no overload chain.

Constraints

  • Variadic function template (typename... Ts), single implementation
  • Use a fold expression — no recursive helper, no manual base case
  • Mixed argument types work (anything with operator<<)
  • One argument produces no separator; zero arguments produce an empty string

Before you code

  • What does ((out << …), ...) expand to for three arguments?
  • Why fold over the comma operator here rather than +?
  • How do you suppress the separator before the first element inside a fold?

Tests

  • #1Joins mixed types with the separator
  • #2Single argument has no separator
  • #3Chars and literals stream too
  • #4Empty pack yields an empty string

Hints

Hint 1

Stream into an std::ostringstream and fold over the comma operator: ((out << … << args), ...).

Hint 2

Track the position with a counter captured outside the fold: std::size_t i = 0; ((out << (i++ ? sep.c_str() : "") << args), ...);.

Editorjoin-with.cpp
Results

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