Re:Rust vs. C++ Formatting
by tialaramex on Monday January 16, 2023 @04:09PM
(#34405504)
Sure, a hypothetical C++ 11 equivalent would e.g. probably not be able to do the trick where we reject bogus formats at compile time, which is something programmers want and which Rust only gets to do by making this a fancy macro whereas C++ 23 is doing it in the actual library code.
[ Parent
| on HN ]
Re:Rust vs. C++ Formatting
by otherjason on Tuesday January 17, 2023 @07:51AM
(#34411829)
fmtlib (https://github.com/fmtlib/fmt), a C++11 formatting library that was the basis for C++20 std::format, is able to do this.
Re:Rust vs. C++ Formatting
by tialaramex on Wednesday January 18, 2023 @04:21AM
(#34424884)
fmtlib does not, in fact, do this on C++ 11 because as explained it doesn't have enough constant evaluation.
The fmtlib code uses a C-style macro to try to handle format errors at compile time, which detects whether it has enough consteval and no-ops if it does not. On a modern C++ with enough consteval it does exactly what you'd expect it to do, but on older compilers it does nothing.
The result is that fmtlib on an older compiler gets you Exceptions, at runtime, for a format that was invalid at compile time, and if you upgrade the compiler it magically switches to compile time errors.
Edited to add quote from fmtlib docs:
"Compile-time checks are enabled by default on compilers that support C++20 consteval. On older compilers you can use the FMT_STRING macro defined in fmt/format.h instead. It requires C++14 and is a no-op in C++11."