Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write format_as for enums of external namespaces in fmt 10.0

Tags:

c++

fmt

For those who don't know, in fmt 10.0, they removed implicit conversions for enums for std::format. Instead you need to bring a generic format_as function to your own namespace. However having this function in your namespace alone does not fix everything because this function does not catch enums that exist other namespaces.

I tried implicit instantiation for enums that exist in other namespaces, however it failed. I tried to import external enums into my namespace using using ExternalEnum = ExternalNS::Enum;, it failed. I tried using namespace ExternalNS;, it also failed.

The only solutions I found are extending the external namespace by adding the same generic format_as function or implicitly casting every enum.

Is there any other solutions or if not which one is the best solution?

like image 653
Atılhan Emre Dursunoğlu Avatar asked Sep 05 '25 08:09

Atılhan Emre Dursunoğlu


1 Answers

With C++20, you can provide a formatter for enums:

template <typename EnumType>
requires std::is_enum_v<EnumType>
struct fmt::formatter<EnumType> : fmt::formatter<std::underlying_type_t<EnumType>>
{
    // Forwards the formatting by casting the enum to its underlying type
    auto format(const EnumType& enumValue, format_context& ctx) const
    {
        return fmt::formatter<std::underlying_type_t<EnumType>>::format(
            static_cast<std::underlying_type_t<EnumType>>(enumValue), ctx);
    }
};

https://godbolt.org/z/ebj1EndG1

like image 90
DasMoeh Avatar answered Sep 08 '25 15:09

DasMoeh