From 83092fc5c65a56ea322bdbf3ffb78339175b0b8f Mon Sep 17 00:00:00 2001 From: SecMeant Date: Sat, 27 Jun 2020 01:22:24 +0200 Subject: [PATCH 1/2] Storing digits in variable, thus removing magic constant from template param check --- README.md | 4 +++- to_string.hpp | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f2c55e1..bf3d129 100644 --- a/README.md +++ b/README.md @@ -48,11 +48,13 @@ The integer/string conversion is done using a simple method I learned over the y (*Note: The below examples of code are not up-to-date, though they still give a general idea of how `to_string` works.*) ```cpp +constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + constexpr to_string_t() { auto ptr = buf + sizeof(buf) / sizeof(buf[0]); *--ptr = '\0'; for (auto n = N < 0 ? -N : N; n; n /= base) - *--ptr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n % base]; + *--ptr = digits[n % base]; if (N < 0) *--ptr = '-'; } diff --git a/to_string.hpp b/to_string.hpp index 1d88b1a..2d18589 100644 --- a/to_string.hpp +++ b/to_string.hpp @@ -9,6 +9,9 @@ #include +constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +constexpr auto digit_count = sizeof(digits) / sizeof(digits[0]); + /** * @struct to_string_t * @brief Provides the ability to convert any integral to a string at compile-time. @@ -17,7 +20,7 @@ */ template, int> = 0, - std::enable_if_t<(base > 1 && base < 37), int> = 0> + std::enable_if_t<(base > 1 && base < digit_count), int> = 0> struct to_string_t { // The lambda calculates what the string length of N will be, so that `buf` // fits to the number perfectly. @@ -35,7 +38,7 @@ struct to_string_t { auto ptr = buf + sizeof(buf) / sizeof(buf[0]); *--ptr = '\0'; for (auto n = N < 0 ? -N : N; n; n /= base) - *--ptr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n % base]; + *--ptr = digits[n % base]; if (N < 0) *--ptr = '-'; } else { -- 2.39.2 From 2717bb70eadf98411dee246de389668ea7033499 Mon Sep 17 00:00:00 2001 From: SecMeant Date: Mon, 29 Jun 2020 19:31:21 +0200 Subject: [PATCH 2/2] Adding constexpr_to_string namespace Namespace is used to prevent pollution of global namespace by digits and digits_count symbols. --- to_string.hpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/to_string.hpp b/to_string.hpp index 63b52ab..2ea6a60 100644 --- a/to_string.hpp +++ b/to_string.hpp @@ -9,6 +9,8 @@ #include +namespace constexpr_to_string { + constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; constexpr auto digit_count = sizeof(digits) / sizeof(digits[0]); @@ -68,10 +70,12 @@ class to_string_t { constexpr const auto end() const noexcept { return buf + size(); } }; +} // namespace constexpr_to_string + /** * Simplifies use of `to_string_t` from `to_string_t()` to `to_string`. */ template -constexpr to_string_t to_string; +constexpr constexpr_to_string::to_string_t to_string; #endif // TCSULLIVAN_TO_STRING_HPP_ -- 2.39.2