enum to string in modern C++11 / C++14 / C++17 and future C++20

后端 未结 28 2248
逝去的感伤
逝去的感伤 2020-11-22 16:57

Contrary to all other similar questions, this question is about using the new C++ features.

  • 2008 c Is there a simple way to convert C++ enum to string?
  • <
28条回答
  •  不知归路
    2020-11-22 17:27

    Back in 2011 I spent a weekend fine-tuning a macro-based solution and ended up never using it.

    My current procedure is to start Vim, copy the enumerators in an empty switch body, start a new macro, transform the first enumerator into a case statement, move the cursor to the beginning of the next line, stop the macro and generate the remaining case statements by running the macro on the other enumerators.

    Vim macros are more fun than C++ macros.

    Real-life example:

    enum class EtherType : uint16_t
    {
        ARP   = 0x0806,
        IPv4  = 0x0800,
        VLAN  = 0x8100,
        IPv6  = 0x86DD
    };
    

    I will create this:

    std::ostream& operator<< (std::ostream& os, EtherType ethertype)
    {
        switch (ethertype)
        {
            case EtherType::ARP : return os << "ARP" ;
            case EtherType::IPv4: return os << "IPv4";
            case EtherType::VLAN: return os << "VLAN";
            case EtherType::IPv6: return os << "IPv6";
            // omit default case to trigger compiler warning for missing cases
        };
        return os << static_cast(ethertype);
    }
    

    And that's how I get by.

    Native support for enum stringification would be much better though. I'm very interested to see the results of the reflection workgroup in C++17.

    An alternative way to do it was posted by @sehe in the comments.

提交回复
热议问题