16

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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • 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

32

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
  • 68,093
  • 33
  • 169
  • 336
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
  • 223,364
  • 34
  • 402
  • 480
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
  • 47,012
  • 14
  • 126
  • 92
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
  • 22,602
  • 44
  • 128
  • 244
DML
  • 494
  • 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,463
  • 2
  • 18
  • 16