Home >Backend Development >C++ >How Can I Easily Convert C Enums to Strings, Handling Typedefs and Unnamed Enums?
Hassle-Free C Enum Conversion to Strings
Suppose you encounter named enums in your C code:
enum MyEnum { FOO, BAR = 0x50 };
And you seek a script to generate a header featuring a conversion function for each enum:
char* enum_to_string(MyEnum t);
With a straightforward implementation like this:
char* enum_to_string(MyEnum t){ switch(t){ case FOO: return "FOO"; case BAR: return "BAR"; default: return "INVALID ENUM"; } }
However, things get tricky with typedefed enums and unnamed C enums. Let's delve into the best solutions:
X-Macros: The Champion
X-macros emerge as the top choice, offering an elegant solution:
#include <iostream> enum Colours { # define X(a) a, # include "colours.def" # undef X ColoursCount }; char const* const colours_str[] = { # define X(a) #a, # include "colours.def" # undef X 0 }; std::ostream& operator<<(std::ostream& os, enum Colours c) { if (c >= ColoursCount || c < 0) return os << "???"; return os << colours_str[c]; } int main() { std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl; }
The accompanying file "colours.def" holds:
X(Red) X(Green) X(Blue) X(Cyan) X(Yellow) X(Magenta)
Customizing String Output
For added flexibility, you can tweak the string output:
#define X(a, b) a, #define X(a, b) b, X(Red, "red") X(Green, "green") // etc.
The above is the detailed content of How Can I Easily Convert C Enums to Strings, Handling Typedefs and Unnamed Enums?. For more information, please follow other related articles on the PHP Chinese website!