Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How could I extend a format-spec for existing type (eg float) in C++?

I want to extend formatting options for floating-point type, preferably preserving some of the existing options. For instance, I want to add a new type specifier for the measurements with units to write like this std::format({:.5mm}, 0.05f) and get my data printed with precision=5, but also multiplied by 1000 and prefixed with ‘mm’. Is that even possible?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The formatting specification for basic types like float are built into the system; you cannot extend them.

You can wrap them in a user-defined type which you can apply whatever formatting to you like. As exemplified in the comments, std::format("{:.5mm}", MyUnit(0.05f)), where MyUnit is your type which has its own formatting specification.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading