Simulant  21.12-194
A portable game engine for Windows, OSX, Linux, Dreamcast, and PSP
arg_parser.h
1 #pragma once
2 
3 #include <map>
4 #include <vector>
5 
6 #include "generic/any/any.h"
7 #include "generic/optional.h"
8 #include "utils/string.h"
9 
10 namespace smlt {
11 enum ArgType {
12  ARG_TYPE_BOOLEAN,
13  ARG_TYPE_STRING,
14  ARG_TYPE_INTEGER,
15  ARG_TYPE_FLOAT
16 };
17 
18 enum ArgCount {
19  ARG_COUNT_ONE,
20  ARG_COUNT_ONE_OR_MANY,
21  ARG_COUNT_ZERO_OR_ONE,
22  ARG_COUNT_ZERO_OR_MANY
23 };
24 
25 class ArgParser {
26 public:
27  typedef std::multimap<std::string, any> Args;
28 
29  void define_arg(
30  const std::string& name,
31  ArgType type,
32  const std::string& help="",
33  const std::string& var_name="",
34  ArgCount count=ARG_COUNT_ONE
35  );
36 
37  template<typename T>
38  optional<T> arg_value(const std::string& name) {
39  auto it = args_.find(name);
40  if(it != args_.end()) {
41  return optional<T>(any_cast<T>(it->second));
42  } else {
43  return optional<T>();
44  }
45  }
46 
47  template<typename T>
48  std::vector<T> arg_value_list(const std::string& name) {
49  std::vector<T> ret;
50 
51  auto it = args_.lower_bound(name);
52  for(; it != args_.upper_bound(name); ++it) {
53  ret.push_back(any_cast<T>(it->second));
54  }
55 
56  return ret;
57  }
58 
59  template<typename T>
60  optional<T> arg_value(const std::string& name, T def) {
61  auto it = args_.find(name);
62  if(it != args_.end()) {
63  return optional<T>(any_cast<T>(it->second));
64  } else {
65  return optional<T>((T) def);
66  }
67  }
68 
69  const Args& parsed_args() const {
70  return args_;
71  }
72 
73  void print_help() const;
74  bool parse_args(int argc, char* argv[]);
75 
76 private:
77  struct DefinedArg {
78  ArgType type;
79  std::string var_name;
80  std::string help;
81  ArgCount count;
82  };
83 
84  std::map<std::string, DefinedArg> defined_args_;
85  Args args_;
86 };
87 
88 }
smlt::ArgParser
Definition: arg_parser.h:25
smlt
Definition: animation.cpp:25
smlt::optional
Definition: optional.h:13