Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have enum of enums in c++?

Tags:

c++

enums

Is it possible to have enum of enums in c++. I have to have something like:

Error types:

  • Type1
  • Type2
  • Type3

Type1:

  • cause1
  • cause2

Type2:

  • cause3
  • cause4

Type3:

  • cause5
  • cause6

Each of these are integer values. They are supposed to be used in a communication protocol stack. At the receiving side the receiver has to decode the type and cause of the error from the values received. If enums can't be used what would be the best way to do it?

like image 497
sajas Avatar asked Mar 15 '13 08:03

sajas


1 Answers

I'm not even sure what an enum of enums would mean. But the usual way of handling this is either to define ranges in a single enum:

enum Errors
{
    type1 = 0x000,
    cause1,
    cause2,

    type2 = 0x100,
    cause3,
    cause4,
    ...
    causeMask = 0xFF,
    typeMask  = 0xFF00
};

Or to simply define separate enums, in separate words, and use unsigned (or unsigned short, or what ever) and a bit of casting for the different causes.

Whatever the solution adopted, I would encapsulate it in a class, so that client code only has to deal with errorType() and errorCause(); errorCause() could even be a template on the error type value. (But somewhere, you'll need explicit specializations for each type value, because the compiler will not otherwise know how to map value to cause type.)

like image 176
James Kanze Avatar answered Oct 14 '22 09:10

James Kanze