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

前端 未结 5 1118
长发绾君心
长发绾君心 2020-12-14 21:06

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
         


        
相关标签:
5条回答
  • 2020-12-14 21:23

    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
      }
    }
    
    0 讨论(0)
  • 2020-12-14 21:32

    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
    }
    
    0 讨论(0)
  • 2020-12-14 21:45

    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 };
    }
    
    0 讨论(0)
  • 2020-12-14 21:46

    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.

    0 讨论(0)
  • 2020-12-14 21:48

    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.

    0 讨论(0)
提交回复
热议问题