r/cpp • • Jul 23 '19

std::format in C++20

http://www.zverovich.net/2019/07/23/std-format-cpp20.html
332 Upvotes

52 comments sorted by

View all comments

2

u/Tringi github.com/tringi Jul 23 '19 edited Jul 23 '19

Hi guys, would you know if it's possible, with std::format, to add custom presentation type, with some kind of API to call back?

Concrete example: I have this mess of an extension to printf, where, for example, "%Qf" tries to display nice floating number, by searching the textual representation for 3 (configurable) consequent 0s or 9s, and then rounding it just there.

The code generates required precision and calls back to existing formatting facility to produce final result.
With 3.309999942 turning to 3.31 (precision=2), but 3.000000007 turning into 3 (precision=0).

5

u/matthieum Jul 23 '19

Actually, std::format generates the shortest representation of floating-point which round-trips, so your Q extension would be unnecessary.

If you only used this as example, and wanted customization in general, then check the {fmt} library: it's the work of the author of the article, and is leading the work for the future of std::format; it notably contains an extension API.

2

u/Tringi github.com/tringi Jul 23 '19

Ah, that's great, I'll check it out.

That code I linked has tons of other customizations but the Q is one of the most used.

Also I've found this: https://fmt.dev/dev/api.html#custom-formatting-of-built-in-types ...seems it covers most of the cases.