Enum equality test

div0 div0 at users.sourceforge.net
Mon Mar 22 12:06:09 PDT 2010


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

bearophile wrote:
> I'm looking for D2 rough edges. I've found that this D2 code
> compiles and doesn't assert at runtime:
> 
> 
> enum Foo { V1 = 10 }
> void main() {
>     assert(Foo.V1 == 10);
> }
> 
> 
> But I think enums and integers are not the same type, and I don't
> want to see D code that hard-codes comparisons between enum instances
> and number literals, so I think an equal between an enum and an int
> has to require a cast:
> 
> assert(cast(int)(Foo.V1) == 10); // OK
>

Spec explicity says enums are convertible to their base type:

http://www.digitalmars.com/d/2.0/enum.html

> 
> That has made me curious, so I've tried C++0x, and it seems in C++0x
> Foo::V1 == 10 gives a compile error ("enum class" is strongly typed
> enum of C++0x):
> 
> 
> enum class Foo { V1 = 10 };
> int main() {
>     int b = Foo::V1 == 10;
> }
> 
> 
> ...>g++ -std=c++0x test.cpp -o test
> test.cpp: In function 'int main()':
> test.cpp:3: error: no match for 'operator==' in '(Foo)10 == 10'
> test.cpp:3: note: candidates are: operator==(int, int) <built-in>
> 
> Do you think this is worth a bug report (with the "accepts-invalid" keyword)?

No. enum class is a specifc new feature of of C++ to prevent the
implicit conversion. Might be worth requesting the feature for D, but
changing the current behaviour of enum could be pain.

Besides, use of enums should be discouraged in general.
It sucks maintaining code where you've thousands of switch statements
all over the place; there's nearly always a better way.

- --
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iD8DBQFLp7+hT9LetA9XoXwRAhG7AKC+eywLlkft+eoTnOHQMr7d/jeKBgCdHZfi
AP8xzYs+j8vaoeTRTyHPbXc=
=KQut
-----END PGP SIGNATURE-----


More information about the Digitalmars-d-learn mailing list