In some other langauges you can specify enums along with states, eg.:
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);
...
This isn't hard to emulate in c++ - but only it easily becomes somewhat verbose.
I know this has been asked before and similar questions exists, e.g. in Build an enum using variadic template parameters, but I wanted to ask this again and have slightly different perspective.
Consider the following 'hand-written' approach:
#pragma warning(error : 4062)
enum tvtype {
black_and_white,
color
};
struct TvType {
tvtype tvtype_;
constexpr TvType(tvtype type) : tvtype_{type} {
}
constexpr operator tvtype() const {
return tvtype_;
}
};
constexpr TvType BlackAndWhite(black_and_white);
constexpr TvType Color(color);
bool hasColor(TvType tv) {
switch (tv) {
case BlackAndWhite:
return false;
//case Color:
//return true;
};
return false;
}
Try it yourself (comment in the two lines in the switch to make it compile)
This method is working well - only it is somewhat verbose.
Using this method it should now be possible to store some extra information along with the enum
value, like a string representation, perhaps adding functions as well, etc.
Also because it's actually an enum
underneath, it's possible for the compiler to check that all cases have been checked in the switch (the example above should generates a compile error due that the 'color' case is outcommented).
I'm interested in a generic / templated way of getting the enum
generated or something similar that fulfills the requirement of compiler checked switch and extensibility.
But in order to templatize the above, it seems the enum should be generated in a (compile-time) programatical way, which leads to the question:
Is it possible to create an enum from a fold expression for instance or failing that from some kind of recursive template ?