C++26: std::format improvements (Part 2) -- Sandor Dargo
In Part 1, we explored the improvements C++26 brings to
std::format
— from better to_string
behavior to compile-time safety checks. In this part, we look at runtime formatting, defect fixes, and support for new types like std::filesystem::path
.
C++26: std::format improvements (Part 2)
by Sandor Dargo
From the article:
Runtime format strings
P2216R3 brought quite some improvements to
std::format
, including compile-time checking for format strings. Sadly, in use cases where format strings were only available at runtime, users had to go with the type-erased formatting version, std::vformat:
std::vformat(str, std::make_format_args(42));
Using two different APIs is not a great user experience, moreover,
std::vformat
was designed to be used by formatting function writers and not by end users. In addition, you might run into undefined behaviour, detailed in the next section.To overcome this situation, P2918R2 adds
std::runtime_format
so you can mark format strings that are only available at run-time. As such you can opt out of compile-time format strings checks. This makes the API cleaner and the user code will read better as it shows better the intentions.