Search code examples
c++c++20standardstype-safetycompile-time-type-checking

Why isn't it an error if the arguments are more than required in std::format?


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?


Solution

  • A couple of reasons.

    1. 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.

    2. 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.