while there are solutions to easily convert an enum to a string, I would like the extra safety benefits of using enum class
. Is there a simple way to convert an enum class
to a string?
(The solution given doesn't work, as enum class can't index an array).
You cannot implicitly convert to the underlying type but you can do it explicitly.
enum class colours : int { red, green, blue };
const char *colour_names[] = { "red", "green", "blue" };
colours mycolour = colours::red;
cout << "the colour is" << colour_names[static_cast<int>(mycolour)];
It's up to you if that is too verbose.