Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum in a namespace

Tags:

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

like image 221
Stals Avatar asked Aug 17 '11 08:08

Stals


People also ask

Should enum be inside class C#?

In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.

What is an enum in C++?

Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.

Can we inherit enum in C#?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.

When should I use enum in C#?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays. Monday is more readable then number 0 when referring to the day in a week.


1 Answers

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:  // ...   } } 
like image 64
Frerich Raabe Avatar answered Oct 27 '22 15:10

Frerich Raabe