So I need log10
functionality to find the number of characters required to store a given integer. But I'd like to get it at compile time to determine the length of char arrays statically based on these integer constants defined in my code. Unfortunately log10
is not a constexpr
function, even the integer version. I could make an integral version like this:
template <typename T>
constexpr enable_if_t<is_integral_v<T>, size_t> intlen(T param) {
size_t result{ 1U };
while(T{} != (param /= T{ 10 })) ++result;
return result;
}
Which will finally allow me to do: const char foo[intlen(13) + 1U]
Does c++ already give me a tool for this or do I have to define my own?
If you only want to get max digits (base10) for given integral (and floating point) type (not specific value, i.e. enough for all values), you can use: std::numeric_limits::max_digits10 and std::numeric_limits::digits10
The value of std::numeric_limits::max_digits10 is the number of base-10 digits that are necessary to uniquely represent all distinct values of the type T
The value of std::numeric_limits::digits10 is the number of base-10 digits that can be represented by the type T without change, that is, any number with this many significant decimal digits can be converted to a value of type T and back to decimal form, without change due to rounding or overflow.
However, if you want to find constexpr
"length" of a specific constant, you'll have to use your custom function.
std::log10
has to be no constexpr
by standard.
As there as no constexpr alternative, you have to write your own version (or use library which provides one).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With