C++ Logo

std-proposals

Advanced search

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

From: Hadriel Kaplan <hkaplan_at_[hidden]>
Date: Fri, 13 Oct 2023 12:24:29 +0000
From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>

> We have already tool to handle custom string using User-defined literals:
> std::string operator ""_w(const char16_t*, size_t);
> Then `F"{aa}"_w` will simply transformed to:
> operator ""_w("{0}", strlen("{0}"), aa); //always use (ptr, size) first to prevent confusion

So if I understand you correctly, you're suggesting to have the user write this:

    std::cout << F"{aa} foo {bb}"_w;

And have the compiler transform it to this:

    std::cout << ""_w("{} foo {}", 9, aa, bb);

...and then what?

Does the user need to provide a templated literal operator, such as:

    template <class... Args>
    std::string operator ""_w(const char*, size_t, Args&&...) { ... }

The above isn't currently legal, and I'm not sure it can be made legal given we already have the string literal operator non-type template from C++20, but let's assume it can - would everyone need to implement such a literal operator?

Or would the standard library come with some default one, that people can use to just do std::format()?

Like defining a reserved one such as `""f`, so that this code:

    std::cout << F"{aa} foo {bb}"f;

would logically do this:

    std::cout << std::format("{} foo {}", aa, bb);

And if it offers that, then why not just have the the f-string conversion add the `f` if there is no suffix already?

Which brings us back to what the paper already proposes now. Except, of course, that the customization would be done a very different way than the paper suggested. Which is fine by me, fwiw.

-hadriel



Juniper Business Use Only

Received on 2023-10-13 12:24:33