#ifndef CMDLINE_H // -*- c++ -*- #define CMDLINE_H /// // Copyright (C) 2003, 2004, Fredrik Arnerup & Rasmus Kaj, See COPYING /// #include #include #include #include #include /** A general-purpose command line option parser. */ class CmdLine { public: struct Error: public std::runtime_error { Error(const std::string &msg) : runtime_error(msg) {} ~Error() throw() {} }; struct UnknownOptionError: public Error { UnknownOptionError(const std::string &option) : Error("Unknown option: \"" + option + "\""), opt(option) {} ~UnknownOptionError() throw() {} const std::string opt; }; struct ArgumentError: public Error { ArgumentError(const std::string &option, bool not_allowed = false) : Error("Argument " + (not_allowed ? std::string("not allowed") : std::string("missing")) + " for : \"" + option + "\""), opt(option) {} ~ArgumentError() throw() {} const std::string opt; }; //** Defines a possible option. */ struct Option { enum ParameterMode { NO_PARAM, REQ_PARAM, OPT_PARAM }; Option(char short_option, const std::string long_option = "", ParameterMode parameter_mode = NO_PARAM, const std::string &description = "", const std::string &p_name = "") : short_opt(short_option), long_opt(long_option), desc(description), param_name(p_name), param_mode(parameter_mode) {} /// Short option. Set to 0 to disable. char short_opt; /// Long option. std::string long_opt; /// Description. Used by print_usage(). std::string desc; /// Name of parameter, if any. Used by print_usage(). std::string param_name; /** Describes whether the option takes a parameter or not. * Only long options accept optional parameters. */ ParameterMode param_mode; /** A unique identifier. * This is set by add_option.() */ int id; }; /// Initialize with command line arguments. CmdLine(int argc, char **argv); /** Register a possible option. * Returns a unique number (> 0) to identiy the option. */ int add_option(Option option); typedef std::pair Arg; typedef std::vector ParsedOptions; /** Return a vector of option id/param pairs. * The id is zero for arguments that are not options. */ ParsedOptions parse(); /// Display help. void print_usage(std::ostream &out); private: bool seen_double_dash; /// "--" turns off parsing typedef std::vector