Queueless
Queueless

Reputation: 113

How to add custom format specifier to fmt

I'm trying to replace a custom type safe format function with calls to fmt. The current implementation supports a 'u' specifier, which prints values as unsigned irregardless of their sign. I would like to add the same functionality to my calls to fmt::vformat.

I tried just substituting 'd' for instances of 'u' but this will not print negative values properly.

I need to know how to inject a custom integer specifier that invokes the current implementation with the value casted to an unsigned integer.

Upvotes: 1

Views: 342

Answers (1)

vitaut
vitaut

Reputation: 55595

You cannot add a new format specifier to a built-in formatter so I recommend just converting to unsigned:

int answer = -42;
fmt::print("{}", unsigned(answer)); // prints 4294967254

https://godbolt.org/z/5bdtgA

Upvotes: 1

Related Questions