I have a custom type, for example
struct custom_type
{
double value;
};
I want to set a custom FMT formatter for this type. I do the following and it works:
namespace fmt
{
template <>
struct formatter<custom_type> {
template <typename ParseContext>
constexpr auto parse(ParseContext &ctx) {
return ctx.begin();
};
template <typename FormatContext>
auto format(const custom_type &v, FormatContext &ctx) {
return format_to(ctx.begin(), "{}", v.value);
}
};
But the problem is, that output format is set by template code, with this "{}"
expression. And I want to give a user opportunity to define the format string himself.
For example:
custom_type v = 10.0;
std::cout << fmt::format("{}", v) << std::endl; // 10
std::cout << fmt::format("{:+f}", v) << std::endl; // 10.000000
How can I do this?
Currently, when I set the custom format string, I get
what(): unknown format specifier
formatter
type is missing a}
after the function. Also, informat_to()
, I believe it should bectx.out()
like all other examples I can find. It doesn't compile for me as it is. – Wring