C++ Logo

std-proposals

Advanced search

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

From: Hadriel Kaplan <hkaplan_at_[hidden]>
Date: Sun, 15 Oct 2023 04:03:54 +0000
[sorry, my previous email seemed to have formatting issues (ironically?); resending and hoping it works]


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.

-hadriel


Juniper Public

Received on 2023-10-15 04:03:59