reflective enums
renoX
renosky at free.fr
Fri Feb 16 15:52:23 PST 2007
Kevin Bealer a écrit :
> == Quote from renoX (renosky at free.fr)'s article
>> - why the name getString instead of the usual toString name?
>
> That could be changed too; I think of toString() as an object method, and
> when adding a static method, I figured I should use a different name to
> avoid conflicting with the method. I didn't really check whether there
> is a real conflict on this.
From my testing, it doesn't trigger a conflict, but I've only tested it
inside one file.
> There is kind of a strangeness with the way I defined this in that you
> creating instances of the Enum!(...) struct is not useful. The type is
> only really interesting for its static properties.
About this I was wondering if it wouldn't be less strange to do a
template like this:
// expected usage: DefEnum!("enum ListEnumFoo {A,B=1};")
template DefEnum(char[] def_enum) {
mixin(def_enum);
static toString(EnumType!(def_enum) x)
{
// function body similar to the inital get_String()
}
}
Advantages:
-The reflective enum type is really an enum type, so it acts like one.
-No weird struct.
-When(If) I can convince Walther that writef("foo %s",x) means really
writef("foo "~x.toString()); we could write:
writef("enum x value is %d and name is %s\n",x,x); and have the correct
result, because toString(ListEnumFoo x) would hide toString(int x) {x
being an enum variable from type ListEnumFoo).
Disadvantage:
No easy way to iterate among the enum values: we cannot do
foreach(v; ListEnumFoo) because now ListEnumFoo is an enum not a struct..
And we cannot pass an enum type as a parameter, other it would be easy
to define function 'keys' and 'values' (like for associative arrays), so
we'd need a dummy parameter, i.e you wouldn't be able to write
foreach (v; ListEnumFoo) {} and
neither foreach (v; ListEnumFoo.values()) {}
but foreach (v; ListEnumFoo.A.values()) {} could perhaps work.
What do you think about this other way to do it?
Regards,
renoX
More information about the Digitalmars-d
mailing list