Coming from a Java background, I find C++\'s enums very lame. I wanted to know how to write Java-like enums (the ones in which the enum values are objects, and can have attr
With C++11's introduction of constexpr
. There's yet another way to implement typed enums. One that works practically the same as normal enums (is stored as an int
variable and can be used in a switch
statement), but also allows them to have member functions.
In the header file you would put:
class Planet {
int index;
public:
static constexpr int length() {return 8;}
Planet() : index(0) {}
constexpr explicit Planet(int index) : index(index) {}
constexpr operator int() const { return index; }
double mass() const;
double radius() const;
double surfaceGravity() const;
};
constexpr Planet PLANET_MERCURY(0);
constexpr Planet PLANET_VENUS(1);
constexpr Planet PLANET_EARTH(2);
// etc.
And in the source file:
static double G = 6.67300E-11;
double Planet::mass() {
switch(index) {
case PLANET_MERCURY: return 3.303e+23;
case PLANET_VENUS: return 4.869e+24;
case PLANET_EARTH: return 5.976e+24;
// Etc.
}
}
double Planet::radius() {
// Similar to mass.
}
double Planet::surfaceGravity() {
return G * mass() / (radius() * radius());
}
Which can then be used as:
double gravityOnMercury = PLANET_MERCURY.SurfaceGravity();
Unfortunately, the enum entries cannot be defined as static constants within the class body. They must be initialized upon declaration, because they are constexpr
, but inside the class, the class is not yet a complete type and thus cannot be instantiated.