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:
- access to
Color
values asColor::Red
. It is really hardly to understand code whenCar::Red
is used, when class have a lot enums, subclasses etc. - use type
Color
as function argument or return value - use variable type
Color
inswitch
I know 3 partial solutions:
- Using embedded class
Color
and enum in it - Using embedded namespace
Color
and enum in it - 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 :)
3 Answers 3
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 };
6 Comments
// Color d = Red; <-- error now
is not giving any error at the moment. Also I can acces the values from the enum declared as a global one by typing their names (e.g cout << Red << endl;
)enum class
or just enum
?enum
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);
};
5 Comments
C++11
feature enum class
.Color
in getter and setter of Car
?Color::
part is not needed here?Color
is intended to be a nested class).enum class
because it's not uniformly supported across all needed platforms.When I want to do something like this I tend to use a namespace and a typedef outside of th namespace (though usually I'm doing this globally rather than inside a class). Something like this:
namespace colors
{
enum Color
{
Red,
Blue
...
}
}
typedef colors::Color Color;
This way you use the namespace to get at the actual colors, but the Color
type itself is still globally accessible:
Color myFav = colors::Red;
8 Comments
colors::Color
every time you want to store an enum value somewhere. As for not giving the enum a name - what if you want to use the enum type later on? I guess you're maybe implying you should just use an int, but why throw away type information (and therefore type-safety) like that?
-std=c++0x
) supportsenum class
, and also allowsColor::Red
for regular enums.