User12547645
User12547645

Reputation: 8437

How to I write type custom conversions for enums?

Let's say I have an enum like this:

enum fruit { apple, oranges };

I would like to write an operator that enables me to write

fruit f = fruit::apple;
std::string s = f; // "Apple"

For a class, I would implement a custom cast-operator. How can I do this for an enum?

Also compare this post, which (kind of) answers the question for enum class.

Upvotes: 1

Views: 216

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29965

One way of doing that would be to have a free function to do the conversion:

#include <cstdio>

enum class fruit { apple, oranges };  // prefer scoped enums

[[nodiscard]] constexpr char const* fruitName(fruit const f) noexcept {
  switch (f) {
    case fruit::apple: return "Apple";
    case fruit::oranges: return "Oranges";
    // most compilers will warn if you don't add all enum values
  }
  return "Error";
}

int main() {
  fruit f = fruit::apple;
  std::puts(fruitName(f));  // prints "Apple"
}

Upvotes: 1

Related Questions