constexpr log10 整数函数

constexpr log10 Function for Integers

所以我需要 log10 功能来查找存储给定整数所需的字符数。但我想在编译时获取它,以根据我的代码中定义的这些整数常量静态确定 char 数组的长度。不幸的是 log10 不是 constexpr 函数,即使是整数版本。我可以像这样制作一个完整的版本:

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;
}

这最终将允许我做:const char foo[intlen(13) + 1U]
是否已经为我提供了一个工具,还是我必须定义自己的工具?

如果你只想获得给定整数(和浮点)类型的最大位数(base10)(不是特定值,即足够所有值),你可以使用: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.

但是,如果您想找到特定常量的 constexpr“长度”,则必须使用您的自定义函数。

std::log10 必须是 no constexpr 按照标准。

由于没有 constexpr 替代方案,您必须编写自己的版本(或使用提供此版本的库)。