Using the C++ fmt library, and given a bare format specifier, is there a way to format a single argument using it?
// example
std::string str = magic_format(".2f", 1.23);
// current method
template <typename T>
std::string magic_format(const std::string spec, const T arg) {
return fmt::format(fmt::format("{{:{}}}", spec), arg);
}
While the above implementation does what I want, I would prefer a way that doesn't require me to build a new temporary string in the process.
You can do this by using formatter<T> directly:
template <typename T>
std::string magic_format(fmt::string_view spec, const T& arg) {
fmt::formatter<T> f;
fmt::format_parse_context parse_ctx(spec);
f.parse(parse_ctx);
std::string str;
auto out = std::back_inserter(str);
using context = fmt::format_context_t<decltype(out), char>;
auto args = fmt::make_format_args<context>(arg);
context format_ctx(out, args, {});
f.format(arg, format_ctx);
return str;
}
Godbolt: https://godbolt.org/z/Ras_QI
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With