top | item 37713560

(no title)

gituliar | 2 years 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 *`.

discuss

order

jasode|2 years 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|2 years 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.

gpderetta|2 years ago

That only works well for dense enums unfortunately.