Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid name conflicts for two enum values with the same name in C++?

Tags:

c++

enums

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?

like image 340
bytecode77 Avatar asked Jun 03 '12 11:06

bytecode77


3 Answers

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 };
}
like image 81
iammilind Avatar answered Oct 08 '22 02:10

iammilind


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.

like image 30
juanchopanza Avatar answered Oct 08 '22 03:10

juanchopanza


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
  }
}
like image 21
Not_a_Golfer Avatar answered Oct 08 '22 04:10

Not_a_Golfer