3 ms·
So far, I'm happy with this simple solution: enum _ : u8 { kMonday, kTuesday, ... kSize }; constexpr const char* toString[kSize] = {
by gituliar 3y ago
So far, I'm happy with this simple solution:
enum _ : u8 {
kMonday,
kTuesday,
...
kSize
};
constexpr const char* toString[kSize] = {
"Monday",
"Tuesday",
...
}
auto day = toString[kTuesday];
Edit: For `constexpr` replace `std::string` with `const char *`.
- gpderetta 3y agoThat only works well for dense enums unfortunately.
- jasode 3y ago>So far, I'm happy with this simple solution: [...] constexpr const char toString[kSize] = { "Monday", "Tuesday", ... } * But you had to manually code that "toString[] = {"Monday",}" Your "simple solution" misses the point of the article which is to have the compiler automatically generating the serialized string representation of the enum without a human programmer having to manually code the switch case statements or array lookups and also avoid manually keep the enum & array in sync. The idea is to have the enum definition itself acting as a "single source of truth" and comparing various language features or libraries to derive the code to write out enum names as strings. In other words, the author is exploring various techniques of pseudo "introspection"/"reflection" for the enum data type.
- gituliar 3y ago> Your "simple solution" misses the point of the article which is to have the compiler automatically generating the serialized string representation of the enum without a human programmer having to manually code the switch case statements or array lookups and also avoid manually keep the enum & array in sync. I agree, in some cases automatic generation might save you some typing. It might be also painful to maintain, as changing a string requires to change a corresponding enum everywhere in the code.
- tommiegannert 3y ago> For `constexpr` replace `std::string` with `const char *`. Or string_view [1], since it's a literal. [1] https://en.cppreference.com/w/cpp/string/basic_string_view https://en.cppreference.com/w/cpp/string/basic_string_view