A safer switch?

grauzone none at example.net
Mon Oct 12 07:48:21 PDT 2009


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.



More information about the Digitalmars-d mailing list