User:Gregorycu
From Cppwiki
|
I am just a regular chatter on #C++. Not as much of a regular as some of the others though...
Strong Enum Idea
As the C++0x standard is not finialised, and the syntax for strong enums has not been decided, let us assume strong_enum is the keyword used.
| Code |
|---|
struct A {
enum Color {red, green, blue} color;
}
int main() {
A foo;
foo.color = A::red; // 1: Valid
foo.color = red; // 2: Invalid
}
|
Example 1 is valid. Example 2 is not. My idea is to make example 2 valid, when strong enums are used. This will only work on strong enums. I want to make strong_enum assignment RHSes always exist at the current scope. Because A::color is a strong enum, there is no ambiguity.
| Code |
|---|
struct A {
strong_enum Color {red, green, blue} color;
}
int main() {
A foo;
int red;
foo.color = red;
}
|
With non-strongly typed enums, this could be a problem. Should the int red, or the enum value red be assigned? This is a strongly typed enum however. The enum value is the ONLY possible valid assignment. There is no ambiguity here. There is one case where there may be ambiguity however:
| Code |
|---|
strong_enum Color {red, green, blue} color;
int main() {
Color foo;
Color blue;
foo = blue;
}
|
Is this assignment from the value of the variable "blue" or assignment of the enum value blue. A solution is that assignment to the value of the variable is assumed, unless the enum value is qualified like so:
| Code |
|---|
foo = Color::blue; |
It should be noted that naming variables the same name as enum values is probably poor style...
Additional note
Perhaps variable names could be enforced such that the above situation would never arise. This would IMHO provide for human readability and consequently ease of maintenance. - baaba
| Code |
|---|
strong_enum Color { red, blue, green };
int main() {
Color shirtcolor = red; // ok
int green = 4; // ok
Color red; // Compiler error: illegal variable name ("red" exists as a member of "Color")
}
|