Search code examples
enumsd

Using simple enumerators in D


Say I have the following enum:

struct Test {
    string value;
}

Test new_test(string value) {
    Test t;
    t.value = value;
    return t;
}

enum Foo : Test {
    A = new_test("a"),
    B = new_test("b"),
    c = new_test("c"),
}

I'm confused as to a few things. How do I pass this around to functions?

void do_something(Foo f) {

}
do_something(Foo.A);

// or

void do_something(Test t) {

}
do_something(Foo.A);

And finally, is there any way I can get the numerical value of the enum for example

A -> 0
B -> 1
C -> 2

Something simple like:

Foo.A.id ???

Solution

  • When you write

     enum Foo {
         A = new_test("a"),
         B = new_test("b"),
         C = new_test("c"),
     }
    

    You're basically creating a named set of values. They have no numerical value, the way you think - they're just regular structs. If you need to know the index of a value in the set (such that getIndex(Foo.C) would return 2), you could use this code:

    // Gets the index of an enum value in the enum it's part of.
    int getIndex(T)(T value) if (is(T == enum)) {
        // Iterate over all the members of the enum, and return the index if it's a match.
        static foreach (i, member; __traits(allMembers, T)) {
            if (value == __traits(getMember, T, member))
                return i;
        }
        return -1;
    }
    

    As for passing it around, either way works, as you may have noticed. Again, there's nothing magical about enums. They're not a number disguised as a Test, and can be used like a Test in every way.