Reputation: 23971
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
Upvotes: 10
Views: 2114
Reputation: 2364
As already told is not possible. But you can consider using a class as enum.
class Day
{
enum _Day{ Sunday, Monday, Tuesday, Wensday, Thursday, Friday, Saturday }
public:
static Day Sun;
static Day Mon;
static Day Tue;
static Day Wen;
static Day Thu;
static Day Fri;
static Day Sat;
operator int() const { return _day; }
int toInt() const { return _day; }
std::string toStr() const { return _name;}
private:
Day(_Day day, std::string name)
: _day(day), _name(std::move(name))
{
}
_Day _day;
std::string _name;
};
Day Day::Mon = Day(_Day::Sun, "Sunday");
Day Day::Mon = Day(_Day::Mon, "Monday");
// ....
Stronger typing, works exactly like an enum, with the additional features you need.
Moreover you could add all the convenience functionality you could desire, for instance:
operator std::string() const;
bool operator==(const Day&);
Day& operator=(const Day&);
Upvotes: 0
Reputation: 1
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.
Upvotes: 9