I've come across a recurring issue in a few of my recent projects in which I find myself using enums to represent state, or type, or something else, and I need to check against a few conditions. Some of these conditions span multiple enums, so I end up with a load of logic in switch
and if
blocks, which I don't like. This is a particular problem when having to cast things to and from the enum, like when the enum is being used to check an int that you're getting from a web request or a calculation.
Is there something in C++ or C# that can be used as a nested enum? Something like this:
enum Animal
{
Mammal
{
Cat,
Dog,
Bear
},
Bird
{
Pigeon,
Hawk,
Ostrich
},
Fish
{
Goldfish,
Trout,
Shark
},
Platypus //srsly what is that thing
};
Obviously, it may or may not be declared like that, but you get the idea. The point is that in code you could use it like Animal thisAnimal = Animal.Mammal.Cat
and then later check if (thisAnimal.IsMember(Animal.Mammal))
or something like that.
I've seen Java's EnumSet, and found them pretty useful, but I don't think they're an exact match for the functionality I'm after. For this example, you'd have to declare an enum with all the animals at one level, and then add them all to the relevant sets. That would mean that when using the original enum, higher-level things like Mammal
or Invertebrate
would appear on the same "level" as something very specific like African Swallow
, which would imply that they were (to some degree) interchangeable, which isn't true. In theory, a nested structure as above might allow you to specify the level of "specificness" needed, so you could get this:
enum Animal::Kingdom.Order.Family.Genus.Species
{ /*stuff*/ }
Organism::Kingdom.Phylum.Class.Order.Family thisThing;
thisThing = Animalia.Cordata; //compiler error
thisThing = Animalia.Chordata.Aves.Passeri.Hirundinidae; //compiles OK
Does a structure like this exist anywhere? If not, how might I build one for C++ and/or C# and have it remain as generic and re-usable as possible?
if (Tenant.Pet.IsMember(Animal::Fish))
because they're only allowed a fish, or something.