代码之家  ›  专栏  ›  技术社区  ›  xmllmx

如果参数超出std::格式的要求,为什么不算错误呢?

  •  2
  • xmllmx  · 技术社区  · 2 年前

    这个 cppref page 在…上 std::format 说:

    提供比格式字符串所需的参数更多的参数不是错误:

    // OK, produces "Hello world!"
    std::format("{} {}!", "Hello", "world", "something"); 
    

    自从 std::格式 进行编译时检查,看看是否 fmt 和参数不匹配,为什么上面的示例代码不被视为错误?

    背后的理由是什么?

    1 回复  |  直到 2 年前
        1
  •  8
  •   n. m. could be an AI    2 年前

    有几个原因。

    1. 您可以在格式字符串中多次使用相同的参数:

       std::fomat("{1},{0},{1}", x, y);
      

      没有理由排除零次提及它。

    2. 它实际上在提供本地化字符串时很方便:

       std::vformat(get_string("Preheat the oven to {} degrees"), temp, temp*9/5+32);
      

      返回的字符串 get_string 将包含 {0} 或 {1} .

    请注意,这与是否进行编译时或运行时检查无关。无论何时执行哪些检查,都应将其视为错误。

    推荐文章