00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #ifndef OPTPARSE_H
00016 #define OPTPARSE_H
00017
00018 #include <map>
00019 #include <vector>
00020 #include <string>
00021 #include <sstream>
00022 #include <stdexcept>
00023
00024 namespace optparse {
00025
00034 typedef enum {STORE_FALSE=0, STORE_TRUE, STORE} action_t;
00035
00040 typedef enum {STRING=0, BOOL, INT, DOUBLE} type_t;
00041
00043 class Option {
00044 public:
00045 Option (std::string shrt, std::string lng, std::string dest,
00046 std::string hlp, action_t act, std::string dfault, type_t type,
00047 std::string allowed_args);
00048 ~Option ();
00049
00057 bool is_allowed(std::string argument);
00058
00059 action_t action;
00060 std::string shrt_flag;
00061 std::string lng_flag;
00062 std::string help;
00063 std::string destination;
00067 std::string dfault_;
00073 type_t type_;
00074 std::string allowed_args_;
00075 };
00076
00077 class OptionError : public std::runtime_error {
00078 public:
00079 OptionError(std::string option, std::string error_msg)
00080 : std::runtime_error("") {
00081 std::ostringstream str;
00082 str << "OptionParser error: option: " << option << ", cause: " << error_msg;
00083 msg_ = str.str();
00084 }
00085 virtual ~OptionError() throw() {}
00090 virtual const char* what() const throw() { return msg_.c_str(); }
00091 protected:
00092 std::string msg_;
00093 };
00094
00096 class OptionParser {
00097 public:
00098 OptionParser (std::string usage="");
00099 virtual ~OptionParser ();
00100
00114 void add_option (std::string shrt_flag, std::string lng_flag,
00115 std::string destination, std::string help="", action_t act=STORE,
00116 type_t type=STRING, std::string dfault="",
00117 std::string allowed_values="");
00118
00119
00120 void parse_args (int argc, char **argv);
00127 void help (std::ostream& os);
00136 std::string type2string(type_t type);
00140 typedef std::map<std::string, std::string> options_type;
00141 options_type options;
00142 std::vector<std::string> arguments;
00143
00144 protected:
00152 virtual void set_option(Option& option, std::string argument);
00153
00154 private:
00155 std::string use_msg;
00156 std::vector<Option> opts;
00157
00158
00159 void find_opt_short(int argc, char **argv, int &index);
00160 void find_opt_long(int argc, char **argv, int &index);
00161 };
00162
00163 }
00164
00165 #endif