Combine enums c++

What I've commonly seen is this:

enum OperationType {
    Comparison = 0x100,
    Arithmetic = 0x200
};        

enum ComparisonType
{
    LT = Comparison,     // "<"
    GT,     // ">"
    EQ,     // "=="
    LTEQ,   // "<="
    GTEQ,   // ">="
    NEQ     // "!="
};
enum ArithmeticType
{
    ADD = Arithmetic,    // "+"
    SUB,    // "-"
    MUL,    // "*"
    DIV,    // "/"
    MOD,    // "%"
};

Which gives you a little more flexibility than simple chaining, because now you can add comparisons without disrupting your Arithmetics, and the Arithmetics and Comparisons don't need to know about eachother. It also becomes trivial to get the type of an enum:

constexpr OperationType getOperationType(unsigned value)
{return static_cast<OperationType>(value&0xFF00);}

A common (but not exceptionally elegant) way to chain enum together (for example if child classes need to extend a unique set) is to have each enum provide a "last" value and use it to start the next:

enum Comparison
{
    LT,     // "<"
    ...
    NEQ,    // "!="
    LastComparison
};

enum Logical
{
    AND = LastComparison,
    OR,
    ...
    LastLogical
};

Unfortunately enums are not designed to be combined, so -unless implementing some factory-based ID generators, but this goes out from enums an compile-time solutions- you cannot do much more of what suggested by Ben Jackson or Mooing Duck.

Consider also that -by a language standpoint- enums are not required to be sequential, so there is no way to know how many of them are into an enum (and also makes few sense to know it, since their values can be anything), hence the compiler cannot provide any automatic mechanism to chain (Jackson) or fork (Duck), hence it's only up to you to organize them. The above cired solutions are both valid, unless you are in the position you cannot define yourself the enumeral values (for example because you've got them from somebody else API).

In this last case, the only possibility is redefine yourself the combination (with other values) and map to the original through a conversion function.

Tags:

C++

Enums

C++11