Skip to content
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

fix format a long value with formatter #2768

Merged
merged 9 commits into from
Jun 12, 2022
16 changes: 12 additions & 4 deletions stl/inc/format
Original file line number Diff line number Diff line change
Expand Up @@ -3286,10 +3286,18 @@ struct _Formatter_base {
_FormatCtx.arg(static_cast<size_t>(_Specs._Dynamic_precision_index)));
}

return _STD visit_format_arg(
_Arg_formatter<typename _FormatContext::iterator, _CharT>{
._Ctx = _STD addressof(_FormatCtx), ._Specs = _STD addressof(_Format_specs)},
basic_format_arg<_FormatContext>{_Val});
using _Storage_type = typename _Format_arg_traits<_FormatContext>::template _Storage_type<_Ty>;
if constexpr (is_same_v<typename basic_format_arg<_FormatContext>::handle, _Storage_type>) {
return _STD visit_format_arg(
_Arg_formatter<typename _FormatContext::iterator, _CharT>{
._Ctx = _STD addressof(_FormatCtx), ._Specs = _STD addressof(_Format_specs)},
basic_format_arg<_FormatContext>{_Val});
} else {
return _STD visit_format_arg(
_Arg_formatter<typename _FormatContext::iterator, _CharT>{
._Ctx = _STD addressof(_FormatCtx), ._Specs = _STD addressof(_Format_specs)},
StephanTLavavej marked this conversation as resolved.
Show resolved Hide resolved
basic_format_arg<_FormatContext>{static_cast<_Storage_type>(_Val)});
}
}

private:
Expand Down
21 changes: 21 additions & 0 deletions tests/std/tests/P0645R10_text_formatting_formatting/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1470,6 +1470,27 @@ void test() {
test_localized_char<wchar_t, wchar_t>();
}

template <class T>
struct Box {
T value;
};

template <class T, class CharT>
struct std::formatter<Box<T>, CharT> : std::formatter<T, CharT> {
template <class FormatContext>
auto format(Box<T> t, FormatContext& fc) const {
return formatter<T, CharT>::format(t.value, fc);
}
};

// Also test GH-2765 "<format>: Cannot format a long value with formatter"
void test_gh_2765() {
StephanTLavavej marked this conversation as resolved.
Show resolved Hide resolved
Box<long> v = {42};
StephanTLavavej marked this conversation as resolved.
Show resolved Hide resolved
assert(format("{:#x}", v) == "0x2a"s);
}

int main() {
test();

test_gh_2765();
}