C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Supporting f-strings in C++

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sun, 15 Oct 2023 00:27:08 -0400
On Sat, Oct 14, 2023 at 11:51 PM Hadriel Kaplan via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> BTW, there _is_ an alternative that might be a good compromise?:
>
> 1. Have the f-string convert the code to use a new C++ template type instead of a std::format() function call - let's call that type a "format_params".
>
> 2. The format_params would essentially be a `tuple<format_string<Args...>, Args...>`, holding the split-apart discrete format-string and arguments.
>
> 3. Give format_params an implicit conversion operator to `std::string` that internally invokes `std::format()` during that.
>
> - That way it will be a `std::format()` invocation by default in most use-cases.
>
> - But one could also write new functions or overloads to accept a `std::format_params<>` type and extract the components for whatever purpose.
>
> 4. Define a new `std::make_format_params(T&&...)` template function to create this new `std::format_params<>` type, and that `make_format_params()` is what an `F"{}"` f-string would actually be converted to.
>
> In other words, this:
>
> std::cout << F"{prefix}_{name}: got {calculate()} for {bits:#06x}";
>
>
> Would be converted to this:
>
> std::cout << ::std::make_format_params("{}_{}: got {} for {:#06x}", prefix, name, calculate(), bits);
>
> The rest of it would be new standard library code.
>
> And it would still work without needing to change what `operator<<(ostream&)` does, or any other function that already accepts a `std::string`.
>
> However, the downside: doing all this would make f-strings no longer work for functions that *only* accept a `std::string_view`, since that would require double conversion.

This is a lot of complexity that seems to exist for the sole purpose
of avoiding typing `std::format`. We already have grammatical
constructs that must appear in specific places in expressions. We have
grammatical constructs that "magically" expand into multiple
expressions.

Leveraging these mechanisms makes a lot more sense than creating a
bunch of new types and such.

Also, in the expansion version, f-strings would only be consumed by
functions that are willing to actually perform the formatting.

Received on 2023-10-15 04:27:30