-
Notifications
You must be signed in to change notification settings - Fork 2.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Padding and Alignment etc doesn't work for user defined types. #787
Comments
The intent of the parse function is to give the formatter control of how to parse the format string, including alignment, padding, etc. To apply the defaults in a situation like this, I believe it is supported to derive your formatter from a pre-existing formatter to get the defaults for parse and similarly delegate to the base class for the format rules. enum class ExampleEnum : char
{
A = '0',
B = '1',
C = '3',
D = '?'
};
template <>
struct fmt::formatter<ExampleEnum> : fmt::formatter<fmt::string_view>
{
using base = fmt::formatter<fmt::string_view>;
template <typename FormatContext>
auto format(const ExampleEnum& e, FormatContext& ctx)
{
switch (e)
{
case ExampleEnum::A:
return base::format("A", ctx);
case ExampleEnum::B:
return base::format("B", ctx);
case ExampleEnum::C:
return base::format("C", ctx);
case ExampleEnum::D:
return base::format("D", ctx);
};
return base::format("NOT_RECOGNISED", ctx);
}
};
TEST(StringFormatTests, ExampleEnum)
{
EXPECT_EQ("A", fmt::format("{}", ExampleEnum::A));
EXPECT_EQ("A ", fmt::format("{:6}", ExampleEnum::A));
} |
This is great. Thanks. p.s. I was following the pattern described here: http://fmtlib.net/latest/api.html#formatting-user-defined-types Which doesn't involve inheriting from Perhaps there could be an example of a formatter that inherits from |
Good idea, added one in 60c662b. |
Hello, I'm trying to make padding and alignment work for user defined types. I'm using 5.0.0.
The following doesn't seem to work at the moment. Apologies if this has already been discussed in another ticket. However, I couldn't find it by searching.
As you can see, fmt can format correctly if you're just formatting something very basic with only
{}
. However as soon as I add padding or alignment, it causes a runtime error.The text was updated successfully, but these errors were encountered: