Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing to enum values by '::' in C++

Tags:

c++

enums

I have class like following:

class Car  
{  
public:  
    Car();  
    // Some functions and members and <b>enums</b>  
    enum Color
    {
        Red,
        Blue,
        Black
    };  
    Color getColor();
    void setColor(Color);  
private:  
    Color myColor;
}

I want to:

  1. access to Color values as Color::Red. It is really hardly to understand code when Car::Red is used, when class have a lot enums, subclasses etc.
  2. use type Color as function argument or return value
  3. use variable type Color in switch

I know 3 partial solutions:

  1. Using embedded class Color and enum in it
  2. Using embedded namespace Color and enum in it
  3. Using enum class

1 and 2 solutions solves a Color::Red accession problem, but I can't use functions like Color getColor() and void setColor(Color).

3 solution has a problem: VS2010 doen't support enum class. GCC v.4.1.2 doesn't support it too. I don't know about later versions of gcc.

Yes, I'm working on cross-platform project.
I have found this solution, but it seems ... heavy.
I hope somebody can help me here :)

like image 727
Jury Avatar asked Apr 10 '12 14:04

Jury


People also ask

How do you find the value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can you index an enum in C?

You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum . Save this answer.

Can we assign value to enum in C?

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.


2 Answers

In current C++ (i.e. C++11 and beyond), you can already access enum values like that:

enum Color { Red };
Color c = Color::Red;
Color d = Red;

You can go further and enforce the use of this notation:

enum class Color { Red };
Color c = Color::Red;
// Color d = Red;   <--  error now

And on a sidenote, you now define the underlying type, which was previously only possible with hacky code (FORCEDWORD or so anyone?):

enum class Color : char { Red };
like image 177
Sebastian Mach Avatar answered Sep 30 '22 18:09

Sebastian Mach


Name the enum inside the nested class (as example one):

class Car
{
public:
    struct Color
    {
        enum Type
        {
            Red,
            Blue,
            Black
        };
    };

    Color::Type getColor();
    void setColor(Color::Type);
};
like image 34
Mark B Avatar answered Sep 30 '22 16:09

Mark B