The root cause of std::formattable failing on custom std::formatter specializations is typically not that your formatter is wrong, but that the standard library implementation has a defect when checking the concept. This issue has been confirmed as a bug on GCC/libstdc++ and has been fixed in GCC 16.
Core Reason
The standard requires that the formattable concept check the format member function using an unspecified output iterator type (fmt-iter-for<charT>). However, GCC is libstdc++ previously used back_insert_iterator<std::string> when checking the concept, while its internal tuple/range formatters assumed the iterator was an internal _Sink_iter type, causing the static_assert(is_same_v<_Out, _Sink_iter<_CharT>>) in the function body to fail when your format function was instantiated.
When your format function returns auto (deduced return type), the compiler must instantiate the entire function body to deduce the return type, thereby triggering this internal assertion. If you use a standard formatter with an explicitly declared return type, this problem typically does not occur.
Solutions
Solution 1: Explicitly declare the return type of format (recommended, works with both old and new GCC)
Change the format function is return type from auto to an explicit type:
template <>
struct std::formatter<Pair> : std::formatter<std::string> {
// Explicitly declare return type instead of using auto
std::format_context::iterator format(const Pair& pair, std::format_context& ctx) const {
return std::formatter<std::string>::format(
std::format("{{{}, {}}}", pair.a, pair.b), ctx);
}
};
This way, the compiler does not need to instantiate the function body when checking the concept, thereby avoiding triggering the internal assertion.
Solution 2: Use a template format function (standard-compliant approach)
Making format a template function so that it can accept any format context type, which also avoids triggering the assertion:
template <>
struct std::formatter<Pair> : std::formatter<std::string> {
template <typename FormatContext>
auto format(const Pair& pair, FormatContext& ctx) const {
return std::formatter<std::string>::format(
std::format("{{{}, {}}}", pair.a, pair.b), ctx);
}
};
This is the practice recommended by the standard, because formattable requires that the formatter can work with any output iterator type . However, note that if your format function internally calls another formatter is format (such as std::formatter<std::string>::format here), that formatter is return type may still need to be compatible with a generic iterator.
Status
This issue has been fixed in GCC is master branch (commit r16-3738-gac1665954058), with the fix expected to be included in GCC 16. If you are using GCC 15 or earlier, use the above workaround; if you are using Clang or MSVC, this issue typically does not occur.