ProblemsTemplatesOne function, many types: if constexpr
IntermediateTemplates

One function, many types: if constexpr

Context

Debug-output serialization has grown four toText overloads and three bugs: bool prints as 1, strings get quoted only on Tuesdays... and every fix lands in four places. Since C++17 this is one template with if constexpr — fold all the cases into a single function that cannot drift apart.

Task

Implement toText(value)one function template that converts a value to text, branching on the type at compile time with if constexpr: bool"true"/"false", integers → decimal digits, std::string → unchanged, floating point → std::to_string. No overload set.

Constraints

  • Exactly one function template — no overloads, no specializations
  • Branch with if constexpr + type traits (std::is_same_v, std::is_integral_v, …)
  • bool must produce "true"/"false" (not "1"/"0") — mind the check order
  • std::string input is returned unchanged

Before you code

  • What happens to the not-taken if constexpr branches during instantiation?
  • Why must the bool check come before the integral check?
  • How would this look with plain (runtime) if — and why would it fail to compile?

Tests

  • #1bool becomes "true"/"false"
  • #2Integers become decimal digits
  • #3std::string passes through unchanged
  • #4Floating point uses to_string

Hints

Hint 1

Chain: if constexpr (std::is_same_v<T, bool>) … else if constexpr (std::is_same_v<T, std::string>) … else if constexpr (std::is_integral_v<T>) … else ….

Hint 2

A plain runtime if would force every branch to compile for every T — return value; does not compile when T is int. That is exactly what if constexpr avoids.

Editorto-text-if-constexpr.cpp
Results

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

One function, many types: if constexpr — CppForge