C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal to add f-strings to C++ as an improvement of string formatting

From: Andrew Tomazos <andrewtomazos_at_[hidden]>
Date: Sat, 31 Dec 2022 17:11:06 +1100
On Thu, Dec 29, 2022 at 4:00 AM Barry Revzin via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On the other hand this:
>
> fmt::print(f"threshold is {threshold}, time is now {time()}\n");
>
> is substantially better (though not much shorter) than this:
>
> fmt::print("threshold is {}, time is now {}\n", threshold, time());
>
> I think this facility is really only worth supporting for format. Plus, I
> think it's exceedingly hard to come up with a way for it to work for both
> format and iostreams to begin with, since their respective syntaxes are so
> different. So there's more value in supporting just the better one.
>

I feel like I've made this proposal before, but I can't seem to find it.

Anyway, the way I was thinking this would be implemented would be that an
f-string literal would have a type like std::format_string<T1,T2,...,Tn>,
and that would contain something like the base format string literal (const
char*), and a tuple of T1,T2,...,Tn where they are the types of the
subexpressions between the braces, and perhaps an array of the index
positions in the format string where they are located.

That way if you want to support these things you write a function template
that uses std::format_string as a parameter, and from that parameter you
can get the information you need to interpolate the arguments into the
output string (or output them, or whatever).

iostream could then provide an overload for std::format_string and likewise
std::print could too, and so on.

This is something vaguely like std::initializer_list.

Received on 2022-12-31 06:11:20