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?
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 };
}
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With