Better enums

This tip submitted by Brent on 2012-08-13 14:24:22. It has been viewed 14298 times.
Rating of 5.9 with 67 votes



Rather than having the enum constants at the same scope as the enum itself, it's possible to nest them similar to C#.

Typical C++:
enum directions { up, down };

directions myDirection = up; //up is in global scope

Better:
NAMED_VALUES_TYPE( directions, { up, down } );

directions myDirection = directions::up; //up is nested

All you need is this gem:

#define NAMED_VALUES_TYPE(type_name, ...) \
struct type_name \
{ \
public: \
enum Values __VA_ARGS__ ; \
type_name() {} \
type_name(Values that) : value(that) { } \
Values operator =(Values that) { value = that; return that; } \
operator Values() const { return value; } \
bool operator ==(Values that) const { return value == that; } \
bool operator !=(Values that) const { return value != that; } \
bool operator ==(type_name that) const { return value == that.value; } \
bool operator !=(type_name that) const { return value != that.value; } \
private: \
Values value; \
}



More tips

Help your fellow programmers! Add a tip!