Skip to content

Commit bc535fe

Browse files
phprushappymonkey1
authored andcommitted
Improve std::complex formatter to be compatible with P2197R0 (fmtlib#3900)
Signed-off-by: Vladislav Shchapov <[email protected]>
1 parent 188d57a commit bc535fe

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

Diff for: include/fmt/std.h

+9-4
Original file line numberDiff line numberDiff line change
@@ -595,10 +595,15 @@ struct formatter<std::complex<F>, Char> : nested_formatter<F, Char> {
595595

596596
template <typename OutputIt>
597597
FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {
598-
auto format = detail::string_literal<Char, '(', '{', '}', '+', '{', '}',
599-
'i', ')'>{};
600-
return fmt::format_to(out, basic_string_view<Char>(format),
601-
f->nested(c.real()), f->nested(c.imag()));
598+
if (c.real() != 0) {
599+
auto format_full = detail::string_literal<Char, '(', '{', '}', '+', '{',
600+
'}', 'i', ')'>{};
601+
return fmt::format_to(out, basic_string_view<Char>(format_full),
602+
f->nested(c.real()), f->nested(c.imag()));
603+
}
604+
auto format_imag = detail::string_literal<Char, '{', '}', 'i'>{};
605+
return fmt::format_to(out, basic_string_view<Char>(format_imag),
606+
f->nested(c.imag()));
602607
}
603608
};
604609

Diff for: test/std-test.cc

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ TEST(std_test, thread_id) {
6767

6868
TEST(std_test, complex) {
6969
EXPECT_EQ(fmt::format("{}", std::complex<double>(1, 2.2)), "(1+2.2i)");
70+
EXPECT_EQ(fmt::format("{}", std::complex<double>(0, 2.2)), "2.2i");
7071
EXPECT_EQ(fmt::format("{:>20.2f}", std::complex<double>(1, 2.2)),
7172
" (1.00+2.20i)");
7273
}

0 commit comments

Comments
 (0)