From 2be778931d2029c3ff121023e5c2c217f69e61d5 Mon Sep 17 00:00:00 2001 From: clyne Date: Fri, 26 Jun 2020 13:42:41 -0400 Subject: [PATCH] Added explanation of code --- README.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/README.md b/README.md index 9b9aeeb..9f9efe1 100644 --- a/README.md +++ b/README.md @@ -25,3 +25,45 @@ Try it [on Compiler Explorer](https://godbolt.org/z/T-MFoh). **Known issues:** * With C++17 GCC, `to_string` must be used to initialize variables; otherwise, the integer-string conversion is done at run-time. + +# How it works + +The basic structure of `to_string` is shown below: + +```cpp +template +struct to_string_t { + char buf[]; // Size selection explained later. + constexpr to_string_t() {} // Converts the integer to a string stored in buf. + constexpr operator char *() {} // These allow for the object to be implicitly converted + constexpr operator const char *() {} // to a character pointer. +}; + +template +to_string_t to_string; // Simplifies usage: to_string_t() becomes to_string. +``` + +Since the number and base are template parameters, each differing `to_string` use will get its own character buffer. + +The integer/string conversion is done using a simple method I learned over the years, where the string is built in reverse using `n % base` to calculate the value of the lowest digit: + +```cpp +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]; + if (N < 0) + *--ptr = '-'; +} +``` + +As you may have noticed, `buf` needs to be given a size for all this to work; in fact, the above code relies on the buffer having a size equal to the generated string (or else `buf[0]` would still be uninitialized). This is actually the case: a lambda is used within `buf`'s declaration to count how many characters long the string will ultimately be. This counting is done in a manner similar to conversion loop shown above: + +```cpp +char buf[([] { + unsigned int len = N >= 0 ? 1 : 2; // Need one byte for '\0', two if there'll be a minus + for (auto n = N < 0 ? -N : N; n; len++, n /= base); + return len; + }())]; +```