A safer switch?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Oct 12 08:13:01 PDT 2009


grauzone wrote:
> bearophile wrote:
>> switch (arg) {
>>     case("-s") {
>>         try {
>>           next_arg = iargs.next();
>>           size = toInt(args[idx++]);
>>         } catch (...) {
>>             throw new Exception("...");
>>         }
>>     }
>>     case("-m") {
>>         printMessages = true;
>>     }
>>     case("-p") // just 1 istruction, no {} needed
>>         printResults = true;
>>     case("-h"); // semicolon isn't allowed here
>>         showUsage();
>>     default { // default case may need some care
>>         throw new Exception("...");
>>     }
>> }
> 
> You can do something like this:
> 
> void main(string[] args) {
>     auto t = ["-s"[]: { writefln("handle argument -s"); },
>               "-m": { writefln("handle argument -m"); }];
>     if (auto pcode = args[1] in t) {
>     (*pcode)();
>     } else {
>     //default case
>     }
> }
> 
> Even the ugly and unneeded case labels are gone!
> 
> If you don't mind your ulta-modern switch-case to allocate memory when 
> it's used.
> 
> If you still don't like it, you can do some ugly mixin() and CTFE stuff. 
> Nobody will mind because that's modern D style.

import std.getopt;

void main(string[] args) {
     getopt(args,
         "s", { writefln("handle argument -s"); },
         "-m", { writefln("handle argument -m"); });
     ...
}


Andrei



More information about the Digitalmars-d mailing list