C++ Logo

std-proposals

Advanced search

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

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Fri, 13 Oct 2023 14:48:26 +0200
pt., 13 paź 2023 o 14:24 Hadriel Kaplan <hkaplan_at_[hidden]> napisał(a):
>
> 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?
>

Yes, this is the whole point of this. Indeed this will need some
extension in allowed operators arguments.
But this is in some way a logical extension of current behavior.

This would allow lot more than simply formatting arguments:
```
F"select * from X where y = {x}"_sql; //no sql injection possible
F"add {x} {y}"_asm;
```
This will add lot of interesting usage

> 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?

Whole point is not to hardcode anything in language itself and make it
impossible to use in a freestanding environment.
And make clear who is responsible for managing this literal.
Another thing is future evolution of std lib, at some point it could
be possible `std2`, if current `std` is hardcoded
then a new version of the standard library can't be used for this. Or
optionly `std::format2` will be added.


>
> 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:48:39