Search code examples
c++constexprc-stringsstring-lengthlogarithm

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 already give me a tool for this or do I have to define my own?


Solution

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