The cppref page on std::format
says:
It is not an error to provide more arguments than the format string requires:
// OK, produces "Hello world!"
std::format("{} {}!", "Hello", "world", "something");
Since std::format
has a compile-time check to see if fmt
and arguments mismatch, why isn't the example code above taken as an error?
What's the rationale behind?
A couple of reasons.
You can use the same argument any number of times in the format string:
std::fomat("{1},{0},{1}", x, y);
There is no reason to exclude mentioning it zero times.
It actually comes handy in providing localized strings:
std::vformat(get_string("Preheat the oven to {} degrees"), temp, temp*9/5+32);
The string returned by get_string
would contain either {0}
or {1}
.
Note this has nothing to do with having or not having compile-time or run-time checks. It is (should be) either considered an error or not, regardless of which checks are performed when.