Fix FMT_COMPILE failure with format_as mapped types (#4794)

This commit is contained in:
AMAN UPADHYAY 2026-07-05 14:51:24 +05:30
parent 77b6ff700b
commit 9bfcd80d12
2 changed files with 23 additions and 1 deletions

View File

@ -168,7 +168,13 @@ constexpr auto get_arg_checked(const Args&... args) -> const T& {
template <typename Char>
struct is_compiled_format<code_unit<Char>> : std::true_type {};
// A replacement field that refers to argument N.
template <typename T, typename = void>
struct compile_has_format_as : std::false_type {};
template <typename T>
struct compile_has_format_as<T, void_t<decltype(format_as(std::declval<const T&>()))>> : std::true_type {};
template <typename Char, typename V, int N> struct field {
using char_type = Char;
@ -178,6 +184,8 @@ template <typename Char, typename V, int N> struct field {
if constexpr (std::is_convertible<V, basic_string_view<Char>>::value) {
auto s = basic_string_view<Char>(arg);
return copy<Char>(s.begin(), s.end(), out);
} else if constexpr (compile_has_format_as<V>::value) {
return write<Char>(out, format_as(arg));
} else {
return write<Char>(out, arg);
}

View File

@ -479,3 +479,17 @@ TEST(compile_test, constexpr_string_format) {
EXPECT_TRUE(big);
}
#endif // FMT_USE_CONSTEXPR_STRING
namespace {
struct CompileFormatAsType {
int value;
};
int format_as(CompileFormatAsType f) { return f.value; }
} // namespace
TEST(CompileTest, FormatAs) {
EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), CompileFormatAsType{42}));
}