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 17:13:51 +0000
From: Jonathan Wakely <cxx_at_[hidden]>

> I don't really like being able to call functions, I think I'd feel more comfortable if you could only name lvalues, not use arbitrary expressions. The workaround isn't great though, e.g. with an immediately invoked lambda you'd have to use:
> [c=calculate()]{ return f"{c}"; }()
> instead of:
> f"{calculate()}"

> How much of the feature's usefulness is lost if it can only refer to lvalues, not evaluate expressions?

That topic came up when python added f-strings too (in https://peps.python.org/pep-0498/#supporting-full-python-expressions).

The tl;dr is that they decided to support full expressions because they were too useful to exclude.

For example for trivial things like these would be for C++:

    F"number of entries: {vec.size()}";
    F"{key} exists: {map.contains(key)}";
    F"is valid: {opt.has_value()}";
    F"iteration #{i + 1}";
    F"num missing: {total - found}";


> With reflection in C++ I think this could be done as a user defined literal, using f as a suffix instead of a prefix. But do we want to wait for that? Maybe. If the proposal was a pure library extension I'd say we should just do it, but as it requires changes to how source code is translated, maybe we don't want to make such fundamental changes as a stop gap that could be replaced by a decent reflection system.

Would processing each separate instance of an f-string using reflection be a lot more expensive than a direct source translation, for the compiler?

I'm only asking because f-strings seem to become viral in terms of usage, at least at my day job working on a medium-sized codebase. A quick grep of it shows that we use std::format() (or really fmt::format()) 3,964 times, across ~1k files of a 10k total C++ file branch. ~230 of those 1k files are header files, and some of the uses are inside common preprocessor macros (like some logging macros), so they're actually a lot more than those counts would indicate. And I don't work on a string-centric application; so strings are not even our main thing. :)

Thanks for the feedback!

-hadriel



Juniper Business Use Only

Received on 2023-10-13 17:14:06