enum scope
Meta via Digitalmars-d
digitalmars-d at puremagic.com
Sat Jun 7 04:30:22 PDT 2014
On Thursday, 26 January 2012 at 13:23:43 UTC, Trass3r wrote:
>> It's not type safe in C. But you can wrap it in a struct with
>> alias this instead.
>
> Yep, but in D we have strong enums, so why not use them.
Enums aren't as strongly typed as you would think (or as I would
like). The major problem is that it's incredibly easy to get an
invalid enum value, even without using a cast.
enum Foo
{
one = 1,
two,
three,
}
enum Bar
{
first,
second,
third,
}
void takesFoo(Foo foo)
{
}
void main()
{
int n = Foo.one;
assert(n == 1);
//Luckily, this doesn't compile
//Foo foo1 = n;
int[] arr = new int[](3);
int m = arr[Foo.two];
//Unfortunately, this DOES compile
Foo foo2 = Foo.one - Foo.two;
assert(foo2 == -1);
takesFoo(foo2);
//Fails (thank goodness)
//takesFoo(Bar.third);
//This actually isn't as bad as it looks.
//The result is of type int and thus
//can't be assigned back to a Foo or Bar
assert(Foo.two - Bar.third == 0);
//Fails
//Foo foo3 = Foo.two - Bar.second;
//Fails
//Bar bar = Bar.first - Foo.three;
}
More information about the Digitalmars-d
mailing list