]> code.bitgloo.com Git - clyne/constexpr-to-string.git/summary
 
descriptionCompile-time number-to-string conversion in modern C++
ownerClyne Sullivan
last changeThu, 2 Jan 2025 18:46:46 +0000 (13:46 -0500)

constexpr-to-string

Requires C++14 or later.

Features:

How to use:

The file to_string.hpp provides a to_string utility, which may be used as below:

cpp const char *number = to_string<2147483648999954564, 16>; // produces "1DCD65003B9A1884" puts(number); puts(to_string<-42>); // produces "-42" puts(to_string<30, 2>); // produces "11110"

With to_string, all that will be found in program disassembly are the resulting string literals, as if you wrote the strings yourself.

Try it on Compiler Explorer.

f_to_string.hpp, requiring C++20, provides an f_to_string utility for floating-point conversion:

cpp puts(f_to_string<3.1415926>); // Defaults to 5-point precision: "3.14159" puts(f_to_string<{3.1415926, 7}>); // Specify precision: "3.1415926"

How it works

C++14 greatly expanded the capabilities of compile-time code execution through constexpr. In particular, it allows for non-trivial constructors to be constexpr.

to_string takes advantage of this by providing an object that converts a template-parameter integer to a string using a basic itoa implementation in the constructor. Through an additional constexpr member function, we can calculate the length of the resulting string; this can be used to size the object's string buffer for a perfect fit.

Beyond this, to_string simply provides familiar member functions that allow for iteration and data access. The expansion of the capabilities of auto in C++14 help make these definitions concise.

The floating-point implementation f_to_string takes a similar approach, but requires C++20 as it needs a double_wrapper object to capture the double value. double and float cannot directly be template parameters as of C++20, and a non-type template parameter like the double_wrapper structure was not allowed before C++20.

shortlog
2025-01-02 Clyne Sullivanremove unnecessary const #7 master
2023-02-08 Clyne Sullivansupport c++14
2020-06-29 clynemake digits inline; simplify digit_count
2020-06-29 clyneMatch namespaces
2020-06-29 clyneMerge pull request #3 from SecMeant/digits_array
2020-06-29 SecMeantAdding constexpr_to_string namespace 3/head
2020-06-29 clyneMerge branch 'master' into digits_array
2020-06-28 clyneUpdate README.md
2020-06-28 clyneUpdate readme for f_to_string
2020-06-28 clyneremoved unnecessary base support
2020-06-28 Clyne Sullivanadded f_to_string
2020-06-28 Clyne Sullivanadded f_to_string
2020-06-27 clyneChanged other base instance to signed
2020-06-27 clyneMerge pull request #1 from EnilPajic/patch-1-negative...
2020-06-27 clyneChange base from unsigned to signed 1/head
2020-06-27 clyneMerge branch 'master' into patch-1-negative-minimum...
...
heads
7 months ago master