How can you convert an enum to a string (reflection limitations)?
Short answer
C++ has no built-in enum reflection before C++26 proposals, so enum-to-string is done manually (switch or a map), by code generation (X-macros), or with libraries like magic_enum (which use compile-time tricks).
Advertisement
AModel answer
C++ has no built-in enum reflection before C++26 proposals, so enum-to-string is done manually (switch or a map), by code generation (X-macros), or with libraries like magic_enum (which use compile-time tricks). This is a common pain point; the standard approaches are a switch returning literals or a lookup table.
const char* name(Color c){
switch(c){ case Color::Red: return "Red"; default: return "?"; }
}Real-world example
A logging system maps enum values to names via a switch so logs are human-readable.
Likely follow-ups
- Does C++ have built-in enum reflection? | What library helps?
Related topics