C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Redefine std::to_string in terms of std::format

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Sat, 16 Mar 2024 00:56:04 +0000
On Fri, 15 Mar 2024, 22:56 ஜெய்கணேஷ் குமரன் via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> Hello all,
>
> Currently std::to_string cannot be overloaded for custom user-defined
> types. While you could follow the convention of having a to_string free
> function in the enclosing namespace of a particular type and then rely on
> ADL to resolve the function, it obviously would not work with fundamental
> types unless you using-ed namespace std or std::to_string.
>
> I would prefer being able to std::to_string to stringily any type if
> possible. I believe that it should be based on std::format so that the
> author of a typer can simply specialise std::formatter<T> to get both
> std::to_string and std::format/print working.
>
> std::string to_string(std::formattable<char> auto&& value) { return
> std::format("{}", value); }
>


Yes, this was suggested in passing in
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2587r3.html#proposal


> Granted, specialising std::formatter<T> is a bit more verbose than simply
> having a to_string free or member function. Perhaps you could allow
> formatting, with no format-arguments, a type that just has a to_string free
> function.
>

What I'd really like is for all three of std::to_string, std::format, and
operator<< for std::ostream to work if any one of them works. Or maybe just
have all three work if either a formatter specialization or operator<<
exists.

So a formatter specialization that uses operator<< if it exists, and an
operator<< that uses std::format if that works, with the right constraints
to avoid cycles.




> template <typename T>
> concept has_free_to_string = requires(T const& t)
> {
> { to_string(t) };
> };
>
> template <has_free_to_string T>
> struct std::formatter<T>
> {
> auto constexpr parse(std::format_parse_context& context) { return
> context.begin(); }
>

> auto format(T const& str, std::format_context& context) const
> {
> return std::format_to(context.out(), "{}", to_string(str));
> }
> };
>
> The same thing shall apply for wide strings.
>
> Note: I do not have the time to participate in standardisation in order to
> open formal proposals, but I wish someöne else does based on my ideas.
>
> Regards,
> Jaiganésh Kumaran.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2024-03-16 00:57:25