Skip to content

Is there any way to avoid having to cast an enum every time you want to print it? #643

Closed Answered by persona94
persona94 asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks! Writing a formatter for each enum was infeasible because we have hundreds of enums.

I ended up writing a few template helpers to accomplish this

namespace fmtquill
{

template <class E>
requires std::is_enum_v<E>
auto format_as(E e)
{
    return static_cast<std::underlying_type_t<E>>(e);
}

}
template <class E>
requires std::is_enum_v<E>
auto format_as(E e)
{
    return static_cast<std::underlying_type_t<E>>(e);
}

template <typename T>
using format_as_type = decltype(format_as(std::declval<T>()));

template <class T>
requires requires { typename format_as_type<T>; }
struct fmt::formatter<T> : formatter<format_as_type<T>>
{
    auto format(T e, auto& ctx) const
    {
        retur…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@odygrd
Comment options

Answer selected by persona94
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants