Search⌘ K

Parsing command line

Explore parsing command line inputs in C++17 by using std::variant to hold multiple types safely, including integers, floats, and strings. Understand how to implement TryParseString, leverage std::optional to detect argument presence, and ensure type safety with holds_alternative.

Command line might contain text arguments that could be interpreted in a few ways:

  • as an integer
  • as a floating-point
  • as a boolean flag
  • as a string (not parsed)
  • or some other types…

Simple int and string version

We can build a variant that will hold all the possible options.

Here’s a simple version with int and string:

C++
class CmdLine
{
public:
using Arg = std::variant<int, std::string>;
private:
std::map<std::string, Arg> mParsedArgs;
public:
explicit CmdLine(int argc, char** argv) {
ParseArgs(argc, argv);
}
std::optional<Arg> Find(const std::string& name) const;
// ...
};

Now let’s look at the parsing code! ...