boostorg / describe

A C++14 reflection library
https://boost.org/libs/describe
67 stars 24 forks source link

Provide integration with formatting libraries #29

Closed Julien-Blanc-tgcm closed 2 years ago

Julien-Blanc-tgcm commented 2 years ago

Since the library provides a to_string / from_string method, it also makes sense that it provides integration with c++20 format library. Maybe at least as a sample in the documentation.

An example using libfmt (i currently don't have local access to a compiler with std::format support):

template<typename Type>
struct fmt::formatter<Type,
        std::enable_if_t<
        std::is_enum<Type>::value &&
        std::is_same<decltype(boost::mp11::mp_front<boost::describe::describe_enumerators<Type>>::name), char const* const>::value,
                char>
        > : formatter<std::string_view>
{
        template<typename FormatContext> auto format(Type v, FormatContext& ctx) -> decltype(ctx.out()) {
                std::string_view name = "unknown";
                boost::mp11::mp_for_each<boost::describe::describe_enumerators<Type>>([&](auto EnumValue) {
                        if(EnumValue.value == v)
                                name = EnumValue.name;
                });
                return formatter<std::string_view>::format(name, ctx);
        }
};
pdimov commented 2 years ago

I've added a fmtlib example for described structs/classes, which parallels the std::ostream one. It didn't occur to me to add enum support too. It's kind of trivial using enum_to_string but not quite when the value doesn't have a name if we want to support all the string_view format specs. May be worth a second example.

pdimov commented 2 years ago

A second fmtlib example, this one for enums, added.