I am trying to come up with a way to determine, whether a given format string is valid for a given Type at compile time.

I was expecting for a simple concept to work:

template<typename T> concept Formattable = requires(T p) { std::format("{.2}", p); }; static_assert(Formattable<double>); // OK static_assert(!Formattable<int>); // Fails

Shouldn't this work, since the expression in the requires-clause does not compile with T=int?

So I tried using the internal constexpr-machinery, but that also did not work so easily:

template<typename T> consteval bool formattable() { auto fmt_parse_ctx = std::format_parse_context(".2"); return std::formatter<T>().parse(fmt_parse_ctx) == fmt_parse_ctx.end(); } static_assert(formattable<double>()); // OK static_assert(!formattable<int>()); // formattable<int> does not compile

I am feeling like I am missing some obvious simple way to achieve this. Any hints?

Jens's user avatar

4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.