Link to home
Create AccountLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

multiple enums in single class

Hi Experts,

I have a class that should have two different enums.

class Controller
{
   enum { CmdOne, CmdTwo, CmdThree, etc };
   enum { ValueOne, ValueTwo, ValueThree, etc };

}
When I use them, I want them to be accessed differently( just pointing out they are from different groups)
for example, now, there is no difference between  Controller::CmdOne and Controller::ValueOne,
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Try this:
class Controller
{
enum X { CmdOne, CmdTwo, CmdThree, etc };
enum Y { ValueOne, ValueTwo, ValueThree, etc };
};

Controller::X::CmdOne
Controller::Y::ValueOne
Avatar of ambuli

ASKER

Thank you.  Is it a "normal" way of doing it?
Yes; it is more typical to name them as described than not, and better practice in most cases.  That is because naming them also clarifies what they are.
Avatar of ambuli

ASKER

Thank you both.  I also see some references to using namespace to achieve this.  However, the enum is declared outside the class.  Which one would be better?


namespace Cmd
{
   enum { One, Two, Three };
}

namespace Value
{
   enum {  One, Two, Three  };
}
class Controller
{


};
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ambuli,

You've accepted http:#a37086873 but that won't actually work in standards compliant C++ since the enum's name does not provide a namespace for the enum values.


>>Thank you.  Is it a "normal" way of doing it?

If you are referring to my answer, yes it is a common C++ idiom to encapsulate an enum in a struct. You can, as Slimfinger observes, also use a namespace but that doesn't work so well if you are doing generic programming (you can't pass a namespace as a type to a template). It is; therefore, more common to use a struct to give your enum a named scope.