Skip to content

Compile-time format string checks by default #2022

Closed

Description

@vitaut

In C++20 we can have format string checks with the normal API, no macro or UDL is required (https://godbolt.org/z/qrh3ee):

#include <fmt/format.h>

template <typename... Args>
struct format_str {
  fmt::string_view str;

  template <size_t N>
  consteval format_str(const char (&s)[N]) : str(s) {
    using checker = fmt::detail::format_string_checker<
      char, fmt::detail::error_handler, Args...>;
    fmt::detail::parse_format_string<true>(
      fmt::string_view(s, N), checker(s, {}));
  }
};

template <class... Args>
std::string format(
    format_str<std::type_identity_t<Args>...> fmt,
    const Args&... args) {
  return fmt::format(fmt.str, args...);
}

int main() {
  auto s = format("{:d}", 42);
  fmt::print("{}\n", s);
}

Activity

  1. alexezeder commented on Apr 15, 2021

    @alexezeder
    Contributor

    One small concern here is that compile-time checks work only for format strings that don't have named identifiers since, currently, named arguments are not able to provide their names at compile-time.
    I'm not so concern about the same behavior of compile-time checks invoked by FMT_STRING, because it's kinda extension, which just fails to work with named identifiers by failing a compilation process.
    But it feels strange, at least for me, to disable compile-time checks (that will be enabled by default) only for format strings with named identifiers.

  2. vitaut commented on Apr 16, 2021

    @vitaut
    ContributorAuthor

    Compile-time checks can potentially be made to work with a UDL form of named arguments.

  3. alexezeder commented on Apr 16, 2021

    @alexezeder
    Contributor

    Compile-time checks can potentially be made to work with a UDL form of named arguments.

    But that's only one way of creating named arguments. The problem with fmt::arg(name, value) would still be relevant.

  4. vitaut commented on Apr 16, 2021

    @vitaut
    ContributorAuthor

    The problem with fmt::arg(name, value) would still be relevant.

    Right. Maybe some day we'll have parametric expressions or constexpr arguments that will make it possible.

  5. self-assigned this
    on May 17, 2021
  6. vitaut commented on Jun 7, 2021

    @vitaut
    ContributorAuthor

    Compile-time checks are enabled now in compilers that have working consteval (gcc 10+, clang 11+).

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions