Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to stringify enum values in C++11 without macros?

Tags:

c++

c++11

I know that it's possible to write a "register" macro that will map their values to their string representations. Is there however some new magic in C++11 that makes it possible to do without macros and any registration boilerplate?

To make it clear, I would like to be able to print the identifiers of enum variables, such as:

enum Days { Sunday, Monday, Tuesday };
auto d = Days::Sunday;
std::cout << magic << d;

Should output

Days::Sunday
like image 572
Tamás Szelei Avatar asked Nov 18 '11 16:11

Tamás Szelei


2 Answers

No, this is not really possible. You need macros (preferably) or to extend the compiler for additional tricks (you might extend GCC with plugins or with MELT to provide a special _my_enum_name_builtin function, but I don't think it is a good idea). You could also (assuming the executable is built with debugging information kept) extract the name from debugging information.

If you really need that, a perhaps simpler way is to generate some (C++) code, which is nearly what macros are doing for you. The Qt Moc could be an inspiration for you.

like image 127
Basile Starynkevitch Avatar answered Nov 24 '22 05:11

Basile Starynkevitch


No. Not possible without macros.

like image 37
balki Avatar answered Nov 24 '22 04:11

balki