Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum to string in C++11

Tags:

enums

c++11

I realize this has been asked before more than once on SO but I couldn't find a question explicitly looking for a current solution to this issue with C++11, so here we go again..

Can we conveniently get the string value of an enum with C++11?

I.e. is there (now) any built-in functionality in C++11 that allows us to get a string representation of enum types as in

typedef enum {Linux, Apple, Windows} OS_type;  OS_type myOS = Linux;  cout << myOS 

that would print Linux on the console?

like image 412
cacau Avatar asked Jan 30 '14 12:01

cacau


People also ask

Can we convert enum to string?

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

Can I convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

Can enum contain strings?

No they cannot. They are limited to numeric values of the underlying enum type.

How do I convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.


1 Answers

The longstanding and unnecessary lack of a generic enum-to-string feature in C++ (and C) is a painful one. C++11 didn't address this, and as far as I know neither will C++14.

Personally I'd solve this problem using code generation. The C preprocessor is one way--you can see some other answers linked in the comments here for that. But really I prefer to just write my own code generation specifically for enums. It can then easily generate to_string (char*), from_string, ostream operator<<, istream operator<<, is_valid, and more methods as needed. This approach can be very flexible and powerful, yet it enforces absolute consistency across many enums in a project, and it incurs no runtime cost.

Do it using Python's excellent "mako" package, or in Lua if you're into lightweight, or the CPP if you're against dependencies, or CMake's own facilities for generating code. Lots of ways, but it all comes down to the same thing: you need to generate the code yourself--C++ won't do this for you (unfortunately).

like image 137
John Zwinck Avatar answered Oct 16 '22 05:10

John Zwinck