Getting the string representing the enum value
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Sun Apr 2 13:20:39 PDT 2006
You have the right idea, although I think it would be better to name the X->char[]
function 'toString' and the char[]->X function 'toX' and the map with all capitals.
Convention, you see, and clarity through expressions like:
# X var = X.Apple;
# char[] str = var.toString;
# X another = str.toX;
In fact, if you don't want the char[]->X conversion at all, then the map can be a static
variable of 'toString(X)', to prevent namespace pollution.
One other suggestion: note the rewritten code below:
Ben Gardner wrote:
> I've done that "the hard way" in C.
> Here's an example in D:
>
> /////
> import std.stdio;
> import std.string;
>
> enum X {
> Apple,
> Bat,
> Car,
> }
>
> char [][] X_names = [
> X.Apple : "Apple",
> X.Bat : "Bat",
> X.Car : "Car",
> ];
>
> char [] get_X_name(X e)
> {
> if ((e >= X.min) && (cast(int)e < X_names.length) &&
> (X_names[e] !is null)) {
> return X_names[e];
> }
> return ("invalid");
> }
char[] toString (X value) {
if (auto foo = value in X_NAMES)
return *foo;
return "invalid";
}
> X get_X_id(char [] name)
> {
> for (int idx = 0; idx < X_names.length; idx++) {
> if ((X_names[idx] !is null) && (icmp(X_names[idx], name) == 0))
> return cast(X)idx;
> }
> return cast(X)-1;
> }
X toX (char[] value) {
foreach (id, name; X_NAMES) {
if (icmp(name, value) == 0)
return id;
}
return cast(X)-1;
}
-- Chris Nicholson-Sauls
More information about the Digitalmars-d-learn
mailing list