如何在C++中为现有类型(例如float)扩展格式规范?

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月25日 22:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定