UDAs on enum members
Tomer Filiba via Digitalmars-d
digitalmars-d at puremagic.com
Wed Jul 13 04:57:21 PDT 2016
It would be really nice if I could put UDAs on enum members as
well, e.g.,
enum MyEnum {
@("SOM") SomeMember,
@("ANO") AnotherMemberWithAVeryLongName,
}
I can think of many reasons why that would be desired, but the
concrete one is the following: I have an interchangeable data
format, and my enum might gain members over time. I don't care
about the value of the member, so I don't want to number them
myself, but I can't control where users would choose to place the
new member, so they might cause renumbering of existing members,
breaking the interchangeable format.
So what I wanted is to assign each member a "short stable name"
that would be used to serialize the value (using my own dump/load
functions)... But I had to resort to a long, ugly switch
statement, mapping members to their names and vice versa. The
dumping function uses final-switch, so you won't forget to update
it, but the loading one can't (it takes a string) so it would be
easy to people to forget.
Given that UDAs can be used practically everywhere (including
struct/union members), is there an objection to make them legal
on enum members as well?
And while we're on the subject, why can't enums have methods? At
the risk of sounding as if I like Java (I don't :) ), it's a
really nice language feature. Back to our example:
enum MyEnum {
@("SOM") SomeMember,
@("ANO") AnotherMemberWithAVeryLongName;
string dump() {
... // `this` is a value, not a ref here
}
static MyEnum load(string name) {
...
}
}
Basically just allow a semicolon at the end of the members, after
which methods could appear. Adding members or whatever else Java
has is an overkill -- just use a struct for that. But instead of
lots of dumpMyEnum(MyEnum e)/loadMyEnum(string s) pairs, you
could write myMember.dump()/MyEnum.load(s)
-tomer
More information about the Digitalmars-d
mailing list