Reputation: 1603
Is there a point of doing somthing like this:
namespace status{
enum status{
ok,
error
};
}
and use it like that status::ok
Or should i do this:
enum status{
status_ok,
status_error
};
and use it like this status_ok
?
Update: With C++11 you now should do this:
enum class status {
ok,
error
};
and use like this: status::ok
Upvotes: 23
Views: 20565
Reputation: 94299
I personally don't like the second variation because the status_
part seems redundant to me. The former version avoids that problem, but having a type status::status
looks strange too. Furthermore, a namespace is open to modification, so in case somebody did something like
namespace status {
void error( const char *msg );
}
You would get a compiler error since the function error
clashes with your enum
value.
I prefer to use a third variation:
struct MouseButton {
enum Value {
Left, Middle, Right
};
};
This lets me write functions like
void handleMouseButton( MouseButton::Value b ) {
switch ( b ) {
case MouseButton::Left: // ...
case MouseButton::Middle: // ...
case MouseButton::Right: // ...
}
}
Upvotes: 22
Reputation: 2786
What you want has just been added to C++ when enabling C++0x extensions. However, if you cannot use C++0x features, I suggest to do this:
struct status
{
enum value
{
ok,
error
};
};
With a such declaration you can write:
status::value var = status::ok;
Such a structure will also allow you to declare functions related to the status type inside the struct
scope. For example, the status struct
could contain methods to convert to/from a string.
Upvotes: 7
Reputation: 69988
If you are not worried about using enum status
type as such, then you can keep it anonymous.
namespace status{
enum { // <--- no name
ok,
error
};
}
Upvotes: 4
Reputation: 13382
Firstly you should access enum
s using the scope operator, ::
not the dot .
operator; i.e. status::ok
Both are fine it's what you feel would be more readable. Note you can also use (without the namespace
)
enum status{
ok,
error
}
and still use status::ok
but some compilers will warn you that the extra status::
is unnecessary.
EDIT: Accessing an enum
using ::
seems to work only with MS visual-c++
Upvotes: 1
Reputation: 17705
I prefer the namespace approach, as it allows using namespace
and using the shorter enum values if only one enum is used in a piece of code.
It's mostly a matter of personal preference, however, I feel that solving (potential) name clashes in C++ is best done using namespaces, as that's the point of having namespaces in the first place.
Upvotes: 1