C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Format output-streamable types?

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 12 Dec 2024 21:20:10 +0000
On Thu, 12 Dec 2024 at 20:24, Robin Savonen Söderholm via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Ok, so just a proposal to add more formatter specialisations?
>

See https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1636r2.pdf

Formatters for thread::id and filesystem::path have now been added, the
rest haven't.



> Users wanting "auto conversions" would have to implement them themselves.
>

I like the idea of some kind of reuse between operator<< and
std::formatter, maybe opt-in. I see no reason why we would ever want to
completely remove basic_ostream.

We could have a variable template like:

template<typename T>
  constexpr bool formatter_uses_ostream_insertion = false;

and then define a formatter specialization that only supports empty format
specs and uses operator<< to produce a string/wstring:

template<typename T>
requires formatter_uses_ostream_insertion<T>
class formatter<T> // ...

We could also provide the reverse opt-in, so that ostream insertion uses
std::format (or std::format_to) to write to the ostream.

And we could provide a generic std::to_string(T) function which uses
std::format if the type is formattable, and operator<< if that works (and
is ill-formed otherwise).

There's lots of room for improvement in this space.

Received on 2024-12-12 21:21:30