Skip to content
Snippets Groups Projects
options.h 2.09 KiB
Newer Older
David Flitney's avatar
David Flitney committed
// $Id$
#if !defined(OPTIONS_H)
#define OPTIONS_H

#include <string>
#include <vector>

#define POSIX_SOURCE 1

class BaseOption {
public:
  typedef enum { 
    no_argument = 0, requires_argument, optional_argument 
  } ArgFlag;
  
  BaseOption(const string& k, const string& ht, bool c, ArgFlag f): 
    key_(k), help_text_(ht), arg_flag_(f), 
    unset_(true), compulsory_(c) {}

  bool compulsory() { return compulsory_; }
  bool required() { return arg_flag_ == requires_argument; }
  bool optional() { return arg_flag_ == optional_argument; }
  bool set() { return !unset_; }
  bool unset() { return unset_; }
  bool has_arg() { return arg_flag_ != no_argument; }
  bool matches(const string& arg);
  const string& key() const { return key_; }
  const string& help_text() const { return help_text_; }

  virtual void value(const string& vs) = 0;

  virtual ~BaseOption() {}

private:
  string key_, help_text_;
  ArgFlag arg_flag_;

protected:
  bool unset_, compulsory_;
};

void string_to_T(bool &b, const string& s); 
void string_to_T(string& d, const string& s); 
void string_to_T(int& i, const string& s); 
void string_to_T(float& v, const string& s); 

template<class T> class Option: public BaseOption {
public:
  Option(const string& k, const T& v, const string& ht,
	 bool c, ArgFlag f = no_argument): 
    BaseOption(k, ht, c, f), default_(v), value_(v) {}

  void value(const string& vs) { 
    string_to_T(value_, vs); unset_ = false; 
  }
  const T& value() { return value_; }
  const T& default_value() { return default_; }
  virtual ~Option() {}

private:
  Option() {}
  
  T default_, value_;
};

class OptionParser {
public:
  OptionParser(const string& p, const string& e): progname_(p), example_(e) {}

  void add(BaseOption& o) { options_.push_back(&o); }
  void usage();
  BaseOption * operator[](const string& key);
  bool check_compulsory_arguments(bool verbose=false);
  unsigned int parse_command_line(unsigned int argc, char **argv);
  
  ~OptionParser() {}

private:
  unsigned int argc_; char **argv_;
  string progname_, example_;
  typedef vector<BaseOption *> Options;
  Options options_;
};

#endif