Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 'ToString()' an enum in C++? [duplicate]

Tags:

c++

How do I 'ToString()' an enum in C++?

In Java and C# I would just call ToString.

enum Colours
{
    Red =0,
    Green=1,
    Blue=2
};

I need to create a string like: "Invalid colour '" + colour + "' selected."

like image 577
CodingHero Avatar asked Feb 05 '12 15:02

CodingHero


People also ask

What happens if you toString an enum?

ToString(String)Converts the value of this instance to its equivalent string representation using the specified format.

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Does enum have toString?

The Java Enum has two methods that retrieve that value of an enum constant, name() and toString().

Can we override toString method in enum?

The toString() method of Enum class returns the name of this enum constant, as the declaration contains. The toString() method can be overridden, although it's not essential.


1 Answers

While this is commonly done through switches, I prefer arrays:

#include <iostream>

namespace foo {
  enum Colors { BLUE = 0, RED, GREEN, SIZE_OF_ENUM };
  static const char* ColorNames[] = { "blue", "red", "green" };

  // statically check that the size of ColorNames fits the number of Colors
  static_assert(sizeof(foo::ColorNames)/sizeof(char*) == foo::SIZE_OF_ENUM
    , "sizes dont match");
} // foo

int main()
{
  std::cout << foo::ColorNames[foo::BLUE] << std::endl;
  return 0;
}

The explicit array size has the benefit of generating a compile time error should the size of the enum change and you forget to add the appropriate string.

Alternatively, there is Boost.Enum in the Boost vault. The library hasn't been officially released but is quite stable and provides what you want. I wouldn't recommend it to a novice though.

like image 106
pmr Avatar answered Oct 24 '22 10:10

pmr