英文:
How could I extend a format-spec for existing type (eg float) in C++?
问题
我想扩展浮点类型的格式选项,最好保留一些现有选项。例如,我想添加一个新的“type”指示符,用于带单位的测量,以便像这样编写:std::format({:.5mm}, 0.05f)
,并且以precision=5
打印我的数据,但也要乘以1000并以'mm'为前缀。这种操作是否可能?
英文:
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?
答案1
得分: 5
基本类型如 float
的格式规范是内置的,无法扩展。
可以 将它们封装在用户定义的类型中,并对其应用任意格式。 如示例中所示,std::format("{:.5mm}", MyUnit(0.05f))
,其中 MyUnit
是您的类型,具有自己的格式规范。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论