Why is this an issue?
std::format
and the related formatting functions provide the possibility to specify the desired length and padding of the textual
representation of the argument through the width and precision options. The value of each of these options can be specified:
- statically, by placing the desired value in a format specification
- or dynamically, by using
{}
or {arg-id}
to refer to a complementary function argument.
When dynamic values are used either for the width or precision, an std::format_error
exception is thrown if the corresponding argument
is not a built-in integer. This rule raises an issue when the argument used for the width or precision is not an integer.
Noncompliant code example
std::cout << std::format("{0:*^{1}}", s, 5.0) << std::endl; // Noncompliant, width argument is not integer
std::cout << std::format("{0:*^10.{1}}", d, "3") << std::endl; // Noncompliant, precision argument is not integer
std::cout << std::format("{0:*^{1}.{2}}", d, "12", 4.0) << std::endl; // Noncompliant, neither width nor precision arguments are integer
std::cout << std::format("{0:*^{1}.{2}}", s, "17", 5.0) << std::endl; // Noncompliant, both width precision arguments are not integer
std::cout << std::format("{:*^{}.{}} {}", s, d, maxLen, maxLen + 2) << std::endl; // Noncompliant, second argument (d) is interpreted as width
Compliant solution
std::cout << std::format("{0:*^{1}}", s, 5) << std::endl; // Compliant
std::cout << std::format("{0:*^10.3}", d) << std::endl; // Compliant
std::cout << std::format("{0:*^{1}.{2}}", d, 12, 4) << std::endl; // Compliant
std::cout << std::format("{0:*^17.5}", s, "17", 5.0) << std::endl; // Compliant
std::cout << std::format("{0:*^{2}.{3}} {1}", s, d, maxLen, maxLen + 2) << std::endl; // Compliant