ProblemsTemplatesHow many digits, compiler?
IntermediateTemplates

How many digits, compiler?

Context

A fixed-width formatter sizes its buffers from template parameters — so the digit count of those parameters has to be a compile-time constant too. Divide by ten until it runs out; the only question is expressing that as a recursion the compiler evaluates.

Task

Implement DigitCount<N>::value — the number of decimal digits of N, computed at compile time. DigitCount<12345>::value == 5.

Constraints

  • Single digits give 1; DigitCount<12>::value == 2 and so on
  • Works up to 12-digit values (use unsigned long long)
  • Usable in static_assert
  • No string conversions, digits only

Before you code

  • What is the base case of the recursion?
  • Why must the template parameter be unsigned long long and not int?
  • How would you extend this to an arbitrary base?

Tests

  • #1Digit counts
  • #2Boundaries around powers of ten

Hints

Hint 1

N below 10 is one digit — the base. Otherwise it is 1 + the digits of N / 10.

Hint 2

In C++17 without requires, dispatch the base case through a helper: a bool non-type parameter or a constexpr function both work.

Editordigit-count.cpp
Results

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