Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get enum item name from its value

Tags:

c++

enums

I declared a enum type as this,

enum WeekEnum { Mon = 0; Tue = 1; Wed = 2; Thu = 3; Fri = 4; Sat = 5; Sun = 6; }; 

How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc."

I already have a function as this

Log(Today is "2", enjoy! );

And now I want the output below

Today is Wed, enjoy

like image 517
Nano HE Avatar asked Jul 30 '12 01:07

Nano HE


People also ask

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do you find the value of an enum number?

You can use: int i = Convert. ToInt32(e); int i = (int)(object)e; int i = (int)Enum. Parse(e.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


2 Answers

You can't directly, enum in C++ are not like Java enums.

The usual approach is to create a std::map<WeekEnum,std::string>.

std::map<WeekEnum,std::string> m; m[Mon] = "Monday"; //... m[Sun] = "Sunday"; 
like image 68
Luchian Grigore Avatar answered Sep 17 '22 19:09

Luchian Grigore


Here is another neat trick to define enum using X Macro:

#include <iostream>  #define WEEK_DAYS \ X(MON, "Monday", true) \ X(TUE, "Tuesday", true) \ X(WED, "Wednesday", true) \ X(THU, "Thursday", true) \ X(FRI, "Friday", true) \ X(SAT, "Saturday", false) \ X(SUN, "Sunday", false)  #define X(day, name, workday) day, enum WeekDay : size_t {     WEEK_DAYS }; #undef X  #define X(day, name, workday) name, char const *weekday_name[] = {     WEEK_DAYS }; #undef X  #define X(day, name, workday) workday, bool weekday_workday[] {     WEEK_DAYS }; #undef X  int main() {     std::cout << "Enum value: " << WeekDay::THU << std::endl;     std::cout << "Name string: " << weekday_name[WeekDay::THU] << std::endl;     std::cout << std::boolalpha << "Work day: " << weekday_workday[WeekDay::THU] << std::endl;      WeekDay wd = SUN;     std::cout << "Enum value: " << wd << std::endl;     std::cout << "Name string: " << weekday_name[wd] << std::endl;     std::cout << std::boolalpha << "Work day: " << weekday_workday[wd] << std::endl;      return 0; } 

Live Demo: https://ideone.com/bPAVTM

Outputs:

Enum value: 3 Name string: Thursday Work day: true Enum value: 6 Name string: Sunday Work day: false 
like image 20
Killzone Kid Avatar answered Sep 18 '22 19:09

Killzone Kid