Addendum: Command Line Flags in C++

Handling Positional Arguments

In the Reddit comments for the original Command Line Flags post there was an interesting discussion about what to do for positional parameters when the user wants to pass an argument that matches an existing flag. /u/AlmaemberTheGreat pointed out the standard way to do this in the Unix world is to handle a pseudo-flag: --.

The intent being when -- is encountered the remaining command line arguments should be interpreted positionally. Adding this to the original parse function is both simple and illustrative of the flexibility of the approach.

Solution

Let’s assume we have the same MySettings struct as laid out in Figure 1, but this time both infile and outfile are positional arguments. To adapt the final parser, let’s first write a small helper function that knows how to handle positional arguments. We’ll assume that infile is the first positional argument (if not already provided) and outfile is the second (if not already provided).

All that’s left to do is add this to the original Figure 5 parser: