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.