(no title)
gituliar | 2 years ago
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 *`.
jasode|2 years ago
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|2 years ago
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.
gpderetta|2 years ago
tommiegannert|2 years ago
Or string_view [1], since it's a literal.
[1] https://en.cppreference.com/w/cpp/string/basic_string_view