How to search for an enum by values and why enum items aren't unique
stunaep via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 19 21:03:23 PDT 2016
How can I search for an enum by its values? For example I have
>struct TestTraits {
> int value1;
> string value2;
>}
>
>enum Test : TestTraits {
> TEST = TestTraits(1, "test1"),
> TESTING = TestTraits(5, "test5")
>}
and I have the int 5 and need to find TESTING with it.
In java I would create a SearchableEnum interface, make all
searchable enums implement it and use this method to find them.
>public static <T extends SearchableEnum> T find(T[] vals, int
>id) {
> for (T val : vals) {
> if (id == val.getId()) {
> return val;
> }
> }
> return null;
>}
But the way enums work in D doesn't seem to permit this.
And why on earth are different enum items with the same values
equal to each other? Say I have an enum called DrawableShape
>struct DrawableShapeTraits {
> bool useAlpha;
> int sideCount;
>}
>
>enum DrawableShape : DrawableShapeTraits {
> RECTANGLE = DrawableShapeTraits(true, 4),
> DIAMOND = DrawableShapeTraits(true, 4),
>}
Now say I have some code that does this
>if(shape == DrawableShape.DIAMOND)
> ... render a diamond
>else if(shape == DrawableShape.RECTANGLE)
> ... render a rectangle
Now even if shape is a DrawableShape.RECTANGLE it's going to
render a DrawableShape.DIAMOND unless I add a dummy value to
differentiate them.
More information about the Digitalmars-d-learn
mailing list