3 This file is part of libmspcore
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
7 #ifndef MSP_CORE_GETOPT_H_
8 #define MSP_CORE_GETOPT_H_
30 OptBase &set_help(const std::string &h) { help=h; return *this; }
31 char get_short() const { return shrt; }
32 const std::string &get_long() const { return lng; }
33 ArgType get_arg_type() const { return arg_type; }
34 const std::string &get_help() const { return help; }
35 unsigned get_seen_count() const { return seen_count; }
36 virtual void process()=0;
37 virtual void process(const std::string &)=0;
38 virtual ~OptBase() { }
46 OptBase(char s, const std::string &l, ArgType a): shrt(s), lng(l), arg_type(a), seen_count(0) { }
49 const std::list<std::string> &get_args() const { return args; }
52 OptBase &add_option(char s, const std::string &l, T &d, ArgType a=NO_ARG)
53 { opts.push_back(new Option<T>(s, l, d, a)); return *opts.back(); }
56 OptBase &add_option(char s, const std::string &l, std::list<T> &d, ArgType a=REQUIRED_ARG)
57 { opts.push_back(new ListOption<std::list<T> >(s, l, d, a)); return *opts.back(); }
60 OptBase &add_option(const std::string &l, T &d, ArgType a)
61 { return add_option(0, l, d, a); }
63 std::string generate_usage(const std::string &) const;
64 std::string generate_help() const;
65 void operator()(unsigned, const char *const *);
70 class Option: public OptBase
73 Option(char s, const std::string &l, T &d, ArgType a): OptBase(s, l, a), data(d) { }
75 virtual void process()
77 if(arg_type==REQUIRED_ARG)
78 throw UsageError("--"+lng+" requires an argument");
83 virtual void process(const std::string &a)
86 throw UsageError("--"+lng+" takes no argument");
89 std::istringstream ss(a);
92 throw UsageError("Invalid argument for --"+lng);
104 class ListOption: public OptBase
107 ListOption(char s, const std::string &l, T &d, ArgType a): OptBase(s, l, a), data(d)
108 { if(arg_type!=REQUIRED_ARG) throw Exception("ListOption with arg_type!=REQUIRED makes no sense"); }
110 virtual void process()
112 throw UsageError("--"+lng+" requires an argument");
115 virtual void process(const std::string &a)
117 typename T::value_type tmp;
118 std::istringstream ss(a);
121 throw UsageError("Invalid argument for --"+lng);
130 std::list<OptBase *> opts;
131 std::list<std::string> args;
133 OptBase &get_option(char);
134 OptBase &get_option(const std::string &);
135 unsigned process_long(const char *const *);
136 unsigned process_short(const char *const *);
139 template<> inline void GetOpt::Option<bool>::process_() { data=true; }
140 template<> inline void GetOpt::Option<unsigned>::process_() { ++data; }