15

Enums in C++ have one major problem: You can't have one name in two different enums like this:

enum Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
}

enum OS
{
    None = 0,
    XP = 1,
    Windows7 = 2
}

So what is the best way to handle this issue in this example?

bytecode77
  • 13,209
  • 30
  • 105
  • 134
  • 1
    If the enum is specific to a class, place it inside a (public section of) the class, then refer to the elements by e.g. ClassName::None and OtherClassName::None. You can also put the enums in namespaces instead. The typical way to namespace them in pure C is via prefixes to each enumerated identifier. – pmdj Jun 03 '12 at 11:12
  • My question http://stackoverflow.com/questions/12972317/count-on-enum-c-automatic answers your question. – sergiol Oct 20 '12 at 15:58
  • enum classes in C++ 11 seem to be a good attempt. But you have to cast it after applying `|`. – bytecode77 Oct 20 '12 at 16:02

5 Answers5

31

In C++03 you can enclose enum inside a struct:

struct Browser
{
  enum eBrowser
  {
    None = 0,
    Chrome = 1,
    Firefox = 2
  };
};

In C++11 make it an enum class:

enum class Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
};

In C++03 namespace also can be wrapped, but personally I find wrapping struct/class better because namespace is more broader. e.g.

// file1.h
namespace X
{
  enum E { OK };
}

// file2.h
namespace X
{
  enum D { OK };
}
iammilind
  • 65,167
  • 30
  • 162
  • 315
13

One option is to put each enum in a different namespace:

namespace Foo {
  enum Browser {
      None = 0,
      Chrome = 1,
      Firefox = 2
  }
}

namespace Bar {
  enum OS {
      None = 0,
      XP = 1,
      Windows7 = 2
  }
}

A better option, if available with your compiler, is to use C++11 enum classes:

enum class Browser { ... }
enum class OS { ... }

See here for a discussion on enum classes.

juanchopanza
  • 216,937
  • 30
  • 383
  • 461
3

Either wrap them in namespaces or in classes:

namespace Browser {
  enum BrowserType
  {
    None = 0,
    Chrome = 1,
    Firefox = 2
  }
}

namespace OS {
   enum OSType  {
      None = 0,
      XP = 1,
      Windows7 = 2
  }
}
Not_a_Golfer
  • 43,930
  • 13
  • 122
  • 88
2

You can use enum class (scoped enums) which is supported in C++11 on up. It is strongly typed and indicates that each enum type is different.

Browser::None != OS::None   

enum class Browser
{
    None = 0,
    Chrome = 1,
    Firefox = 2
}

enum class OS
{
    None = 0,
    XP = 1,
    Windows7 = 2
}
Patryk
  • 20,424
  • 38
  • 116
  • 227
DML
  • 434
  • 5
  • 4
1

How about using scoped vs. unscoped enumeration? c++11 now offers scoped enumeration. An example would be:

enum class Browser : <type> {

};

enum class OS : <type> {

};

Access the enumerated types via an object of the Browser or an object of OS.

user633658
  • 2,265
  • 2
  • 16
  • 16