Skip to content

<format>: Call to next_arg_id may result in unexpected error (regression) #4636

Description

When user-defined formatter calls next_arg_id and format-spec is empty we will get compiler error.

Example:

#include <print>

struct FormatNextArg {};

template <> struct std::formatter<FormatNextArg> {
public:
  template <class ParseContext> constexpr auto parse(ParseContext &ctx) {
    auto it = ctx.begin();
    if (it != ctx.end() && *it != '}') {
      throw std::format_error{"Expected empty spec"};
    }

    arg_id = ctx.next_arg_id();
    return it;
  }

  template <class FormatContext>
  auto format(FormatNextArg, FormatContext &ctx) const {
    return std::format_to(ctx.out(), "arg-id: {}", arg_id);
  }

private:
  size_t arg_id;
};

int main() {
  // std::println("{}, {}", FormatNextArg{}, 0, FormatNextArg{}, "1"); // Does not compile since VS 17.10
  std::println("{:}, {:}", FormatNextArg{}, 2, FormatNextArg{}, "3"); // Works, replacement field is not empty
}

Introduced by: #4078
Compiler explorer (VS 17.9): https://godbolt.org/z/rsje4j1hP

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixedSomething works now, yay!formatC++20/23 format

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions