Two changes for enum handling in getopt

It's better to define enum Color { no, yes } because this enables
writing compact code like if (color) { ... }. Further setting the
variable is done using std.conv's parse which makes the code more
compact and throws if the conversion fails.
This commit is contained in:
Jens K. Mueller 2011-04-06 19:46:54 +02:00
parent 4c71539a9a
commit 29eec1ee23

View file

@ -49,7 +49,7 @@ import std.getopt;
string data = "file.dat"; string data = "file.dat";
int length = 24; int length = 24;
bool verbose; bool verbose;
enum Color { yes, no }; enum Color { no, yes };
Color color; Color color;
void main(string[] args) void main(string[] args)
@ -125,13 +125,13 @@ To set $(D timeout) to $(D 5), invoke the program with either $(D
with an "=" sign: with an "=" sign:
--------- ---------
enum Color { yes, no }; enum Color { no, yes };
Color color; // default initialized to yes Color color; // default initialized to Color.no
getopt(args, "color", &color); getopt(args, "color", &color);
--------- ---------
To set $(D color) to $(D Color.no), invoke the program with either $(D To set $(D color) to $(D Color.yes), invoke the program with either $(D
--color=no) or $(D --color no). --color=yes) or $(D --color yes).
$(LI $(I String options.) If an option is bound to a string, a string $(LI $(I String options.) If an option is bound to a string, a string
is expected as the next option, or right within the option separated is expected as the next option, or right within the option separated
@ -478,11 +478,7 @@ void handleOption(R)(string option, R receiver, ref string[] args,
else static if (is(typeof(*receiver) == enum)) else static if (is(typeof(*receiver) == enum))
{ {
// enum receiver // enum receiver
foreach (s; __traits(allMembers, typeof(*receiver))) *receiver = parse!(typeof(*receiver))(val);
{
if (s == val)
*receiver = mixin(typeof(*receiver).stringof ~ "." ~ val);
}
} }
else static if (is(typeof(*receiver) == string)) else static if (is(typeof(*receiver) == string))
{ {
@ -639,16 +635,16 @@ unittest
getopt(args, "paranoid+", &paranoid); getopt(args, "paranoid+", &paranoid);
assert(paranoid == 5, to!(string)(paranoid)); assert(paranoid == 5, to!(string)(paranoid));
enum Color { yes, no }; enum Color { no, yes };
Color color; Color color;
args = (["program.name", "--color=no",]).dup; args = (["program.name", "--color=yes",]).dup;
getopt(args, "color", &color); getopt(args, "color", &color);
assert(color == Color.no, to!(string)(color)); assert(color, to!(string)(color));
color = Color.yes; color = Color.no;
args = (["program.name", "--color", "no",]).dup; args = (["program.name", "--color", "yes",]).dup;
getopt(args, "color", &color); getopt(args, "color", &color);
assert(color == Color.no, to!(string)(color)); assert(color, to!(string)(color));
string data = "file.dat"; string data = "file.dat";
int length = 24; int length = 24;