Given any (signed or unsigned) integer type T how do I best determine the maximum number of characters of its string representation (including the sign) in any base > 0 at compile time?
template <typename T, typename B>
constexpr auto getMaxLengthAsString(B base) -> /* std::uintmax_t ??? */
{ /* ??? */ }
This is useful in some situations where one has to allocate the string beforehand and is not allowed to throw any exceptions during the conversion. A short example for its usefulness would be this:
template <typename T>
void examplePrintValue(T value) noexcept {
constexpr static auto const maxLen = getMaxLengthAsString<T>(10);
/* Ignoring thread safety etc to keep this example short: */
static char buffer[maxLen + 1u];
buffer[maxLen] = '\0';
/* ... real conversion of value to buffer happens here ... */
cout << buffer << endl;
}
Aucun commentaire:
Enregistrer un commentaire