Enum constructors (creating member members)

In D, I am trying to create an enum that has members. I can better explain what I am trying to do with an example where s

and where i

are the sub-members that I am trying to create:


In Python, I can do this:

class Foo(enum.Enum):
    A = "A string", 0
    B = "B string", 1
    C = "C string", 2

    def __init__(self, s, i):
        self.s = s
        self.i = i

print(Foo.A.s)

      


Java can do something like this:

public enum Foo {
    A("A string", 0),
    B("B string", 1),
    C("C string", 2);

    private final String s;
    private final int i;

    Foo(String s, int i) {
        this.s = s;
        this.i =i;
    }
}

      


How do I do this in D? I don't see anything in the official tutorial. If for some reason I can't do it in D, what's a good alternative?

+3


source to share


1 answer


You can create an enum with any type, here we use a tuple (like python) with a small alias to make it easier to type.



import std.stdio;
import std.typecons;

alias FooT = Tuple!(string, "s", int, "i");
enum Foo : FooT {
    A = FooT("A string", 0),
    B = FooT("B string", 1),
    C = FooT("C string", 2),
}


void main(string[] args) {
    writeln(Foo.A.s);
}

      

+6









All Articles