Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr log10 Function for Integers

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?

like image 891
Jonathan Mee Avatar asked Oct 01 '18 12:10

Jonathan Mee


2 Answers

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.

like image 181
Dan M. Avatar answered Oct 18 '22 02:10

Dan M.


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).

like image 44
Jarod42 Avatar answered Oct 18 '22 04:10

Jarod42