I\'d like to know if it is an easy way of determining the maximum number of characters to print a decimal int
.
I know
contains
In C++11 and later, you can do the following:
namespace details {
template
constexpr size_t max_to_string_length_impl(T value) {
return (value >= 0 && value < 10) ? 1 // [0..9] -> 1
: (std::is_signed::value && value < 0 && value > -10) ? 2 // [-9..-1] -> 2
: 1 + max_to_string_length_impl(value / 10); // ..-10] [10.. -> recursion
}
}
template
constexpr size_t max_to_string_length() {
return std::max(
details::max_to_string_length_impl(std::numeric_limits::max()),
details::max_to_string_length_impl(std::numeric_limits::min()));
}