www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Mutually exclusive switches in getopt?

reply Andrej Mitrovic <none none.none> writes:
I don't see this option in getopt, is it there?

e.g. If I want to disallow passing "--loud" and "--quite" at the same time. 
I can understand it would be difficult to implement this with getopt's current
API.

A limited form of this is possible to do inline via a delegate. For example:

bool quiet, loud;

getopt
(
    args, 
    "quiet", { enforce(!loud); quiet = true; },
    "loud",  { enforce(!quiet); loud  = true; },
);

However that scales poorly with more than two arguments, and especially if
they're of a different type.
May 29 2011
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On 2011-05-29 21:43, Andrej Mitrovic wrote:
 I don't see this option in getopt, is it there?
 
 e.g. If I want to disallow passing "--loud" and "--quite" at the same time.
 I can understand it would be difficult to implement this with getopt's
 current API.
 
 A limited form of this is possible to do inline via a delegate. For
 example:
 
 bool quiet, loud;
 
 getopt
 (
     args,
     "quiet", { enforce(!loud); quiet = true; },
     "loud",  { enforce(!quiet); loud  = true; },
 );
 
 However that scales poorly with more than two arguments, and especially if
 they're of a different type.
You give getopt the list of arguments that you expect along with the type that you expect to go with them. What you do with them is entirely up to you. I wouldn't really want getopt to do my error reporting anyway, since I wouldn't want it to be done via exceptions (users shouldn't be seeing exceptions in your typical, non-buggy program). So, I'd say that you should simply take what getopt gives you and then do your own verification as to whether the values it gave you were actually valid. It's not really getopt's job IMHO to be reporting errors. It could do a better job than it does when it comes to throwing exceptions when it's given bad values, but I'd argue that it's still up to the app to handle those exceptions and report errors as is appropriate to that program. - Jonathan M Davis
May 29 2011