C++ Logo

std-proposals

Advanced search

[std-proposals] Newlines in F-strings

From: Hadriel Kaplan <hkaplan_at_[hidden]>
Date: Tue, 24 Oct 2023 23:32:03 +0000
Hi,

While talking with Bengt offline about various use-cases for f-strings, he brought up one that I'm not sure about.

Should this compile? (note the 'R' for raw-string):

FR"(name={
  get_name()
}, time={
  std::system_clock::now()
  :%H:%M:%S
})";

Right now, in the next rev of the draft I'm working on, the above would treated identically as this non-raw f-string:

F"name={\nget_name()\n}, time={\nstd::system_clock::now():%H:%M:%S\n}";


And it would interpolate to this:

std::format("name={}, time={:%H:%M:%S\n}",\n get_name()\n,\n std::system_clock::now());

Note that there are multiple sets of the two characters "\" and "n" within the extracted arguments (not escaped newlines).

So it will fail to compile due to those characters.

---

If you think it should compile, what should the format-string be after interpolation?:

1. "name={}, time={:%H:%M:%S\n}"
or
2. "name={}, time={:%H:%M:%S}"

And if (2), how do we know the programmer didn't want the newline? It is perfectly legal to have one there for chrono formatting, I believe.

---

Personally I think it's ok for this scenario to fail to compile, but I also think it's ok to succeed instead.

The programmer can always do this instead anyway, if they want to split things up:

F"name={ get_name() }, "
F"time={ std::system_clock::now():%H:%M:%S} )";

-hadriel



Juniper Public

Received on 2023-10-24 23:32:12