c++c++17language-lawyerstringify

Why does floating-point std::to_chars not have a default argument?


std::to_chars has these two declarations:

to_chars_result to_chars(char* first, char* last,
                         floating-point-type value);
to_chars_result to_chars(char* first, char* last,
                         floating-point-type value,
                         chars_format fmt);

[charconv.to.chars] states:

The functions that take a floating-point value but not a precision parameter ensure that the string representation consists of the smallest number of characters such that there is at least one digit before the radix point (if present) and parsing the representation using the corresponding from_chars function recovers value exactly.

Given that there are at least 20 overloads of to_chars, it would seem desirable to eliminate some. It sounds like these two could be merged into one:

to_chars_result to_chars(char* first, char* last,
                         floating-point-type value,
                         chars_format fmt = chars_format::general);

However, I vaguely remember there being some difference in behavior between having no chars_format at all and having chars_format::general. Is that true, and what is that difference? Is there an example where they would have different output?


Solution

  • chars_format::general behaves like printf's %g specifier, which chooses the output representation based on the precision P and exponent X as follows:

    This doesn't always result in the shortest representation, unlike the default format. An example is 1234567.8:

    The former is shorter, but since the default precision (6) is not greater than the exponent (6), the latter is chosen by chars_format::general.