2

In the C++20 <format> library, is it possible to insert characters in a placeholder, so that those characters behave like a part of the passed parameter?

For example, I have the following statement:

std::format("Test '{:<{}}'", 123, 5)

which produces Test '123 '.

What I need it to produce is Test '123; ' (note the semicolon after 123 is left-justified together with 123).

In other words, is there a shorter alternative to this?

std::format("Test '{:<{}}'\n", std::format("{};", 123), 5)
ENIAC
  • 813
  • 1
  • 8
  • 19
  • seems like a duplicate for https://stackoverflow.com/questions/59909102/stdformat-of-user-defined-types – user7860670 Jul 26 '23 at 16:06
  • I don't think so. My question is not about user-defined types. – ENIAC Jul 26 '23 at 16:09
  • However user-defined type with corresponding formatter seems to be a solution to your problem. – user7860670 Jul 26 '23 at 16:11
  • user7860670, thank you for commenting! Based on your comment, the answer to my question is "*No, it's not possible.*". Thus, in my case, double `std::format` looks prettier. Else, I'd have to add tons of code for different UDT's. – ENIAC Jul 26 '23 at 16:19
  • As far as I know, about the only way to do this would be to convert to a string first, add the semicolon, then justify the resulting string. – Jerry Coffin Jul 26 '23 at 17:14
  • @JerryCoffin, looks like that. Thank you for commenting! – ENIAC Jul 26 '23 at 17:18
  • @KamilCuk, `123` is just an example. It may be a variable and, therefore, I need more flexible solution than hardcoding every possible value. – ENIAC Jul 27 '23 at 13:23

1 Answers1

0

In other words, is there a shorter alternative to this?

No.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111