Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

this is not constant expression when attempting to specialize a type from fmt::formatter #2379

Closed
cooky922 opened this issue Jun 23, 2021 · 2 comments

Comments

@cooky922
Copy link

From:

#include <iostream>

#define FMT_HEADER_ONLY
#include <fmt/format.h>

using namespace fmt::literals;

struct Point {
    int x;
    int y;
};

template <> struct fmt::formatter<Point> {
    char presentation = 'd';

    constexpr auto parse(format_parse_context& ctx) {
        auto iter = ctx.begin(), end = ctx.end();

        if (iter != end && (*iter == 'd'))
            presentation = *iter++;

        if (iter != end && *iter != '}')
            throw format_error("invalid format");

        return iter;
    }

    template <typename FormatContext>
    auto format(const Point& p, FormatContext& ctx) const { // const is required
        return format_to(
            ctx.out(),
            ((presentation == 'd') ? "({:d}, {:d})" : "({}, {})"),
            p.x, p.y
        );
    }
};

int main() {

    const Point p1 {10, 15};

    std::cout << fmt::format("Point: {:d}", p1);

}

It won't compile (I'm using GCC 11, and using fmt 8.0.0 recently), and the error message is:

<source> | error: 'this' is not a constant expression |
@foonathan
Copy link
Contributor

Godbolt link: https://godbolt.org/z/4f9WGMEs1

@alexezeder
Copy link
Contributor

I was wondering how it's possible that format() is invoked at compile-time and then with help of Clang realized that:

((presentation == 'd') ? "({:d}, {:d})" : "({}, {})"),

is trying to be converted to fmt::basic_format_string by calling consteval constructor. Anyway, to fix this error you can:

  • wrap this line to fmt::runtime():
          return format_to(
              ctx.out(),
              fmt::runtime((presentation == 'd') ? "({:d}, {:d})" : "({}, {})"),
              p.x, p.y
          );
  • use separate if branches here:
          if (presentation == 'd') {
              return fmt::format_to(ctx.out(), "({:d}, {:d})", p.x, p.y);
          } else {
              return fmt::format_to(ctx.out(), "({}, {})", p.x, p.y);
          }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants