Implicit enum conversions are a stupid PITA
bearophile
bearophileHUGS at lycos.com
Wed Mar 24 09:14:20 PDT 2010
To invent a software you can first find the best syntax. This seems a nice syntax, very similar to the enum one (that ubyte is optional):
flags ubyte Todo {
do_nothing,
walk_dog,
cook_breakfast,
deliver_newspaper,
visit_miss_kerbopple,
wash_covers
}
Todo todo = Todo.walk_dog | Todo.deliver_newspaper | Todo.wash_covers;
if (todo == (Todo.walk_dog | Todo.deliver_newspaper)) { ...
if ((Todo.walk_dog | Todo.deliver_newspaper) in todo) { ...
if ((Todo.walk_dog | Todo.deliver_newspaper) & todo) { ...
assert((Todo.walk_dog | Todo.walk_dog) == Todo.walk_dog); // OK
A way to implement it with current D2 syntax:
alias Flags!(ubyte, "do_nothing",
"walk_dog"
"cook_breakfast"
"deliver_newspaper"
"visit_miss_kerbopple"
"wash_covers") Todo;
Where Flags defines a struct, "do_nothing" are compile-time constants. It can overload 8 operators:
= == | |= in & &= opBool
The operator ! too can be defined, but I think it looks too much like the | so it can be omitted (other operators like ^ and ~ are possible).
Something like this can't work if enums become tidier:
enum ubyte Todo {
mixin(Flags);
do_nothing,
walk_dog,
cook_breakfast,
deliver_newspaper,
visit_miss_kerbopple,
wash_covers
}
I don't like this:
mixin(Flags("
enum ubyte Todo {
do_nothing,
walk_dog,
cook_breakfast,
deliver_newspaper,
visit_miss_kerbopple,
wash_covers
}
"));
Something like can worl, but it's not nice:
struct Todo {
mixin(Fields!(ubyte, "do_nothing",
"walk_dog"
"cook_breakfast"
"deliver_newspaper"
"visit_miss_kerbopple"
"wash_covers");
}
Once the programmer can define attributes, it can be doable this syntax that adds the required methods to the enum, but I am not sure:
@fields enum ubyte Todo {
do_nothing,
walk_dog,
cook_breakfast,
deliver_newspaper,
visit_miss_kerbopple,
wash_covers
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list