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?
const char foo [] = "13"
? That will initialisefoo
as an array of threechar
, without the need to type13
twice. – Cordobalog10
is notconstexpr
and also has come up with a solution. What other tools he is asking for? – Extrauterinechar buffer[intlen(UINT_MAX)+1u];
which creates a buffer big enough to hold any unsigned int. – Nonchalantchar buffer[std::numeric_limits<unsigned>::digits10 + 1]
. BTW: what downvotes are you referring to in your previous comment? - as far as I can see this question has only been upvoted twice. – Cordobafoo
at runtime. – Whimseystrlen(your string) + 1
, nothing to do with integers. Same when assigning literals, compiler can deduce the length automatically. If you want to calculate integral log10 and compile-time, when you'll have to use your function. What's wrong with it and why do you think it's not a "tool" c++ gives you? – Extrauterine#define FOO 13
and#define BAR 42
now I want achar[]
that will exactly contain these numbers along with the value inconstexpr size_t formatting
. I want to be able to do something like:const char foo[intlen(13) + formatting + intlen(42) + 1U]
does that less toy example make sense? My hope was that there was already something available to me in the standard and I didn't have to authorintlen
– Whimseychar a[] = "abc" "123" "0.15";
, the compiler will deduce its size automatically. – Extrauterineconstexpr
. If your string has compile-time computable size, then you can implement it. C++14constexpr
facilities are rather powerful. – Extrauterine