Loading...
Searching...
No Matches
option.h
Go to the documentation of this file.
1#ifndef _BBM_OPTION_H_
2#define _BBM_OPTION_H_
3
4#include <map>
5#include <string>
6#include <stdexcept>
7
9#include "util/string_util.h"
10
11
12/************************************************************************/
13/*! \file option.h
14 \brief Simple command line option parser
15*************************************************************************/
16
17namespace bbm {
18
20 {
21 //! \brief Parse the options from the commandline arguments (argc,argv)
22 inline option_parser(int argc, char** argv)
23 {
24 for(size_t idx = 1; idx < size_t(argc); ++idx)
25 {
26 auto [key, val] = bbm::string::split_eq(argv[idx]);
27
28 // case 1: key = val
29 if(key != "") _map[key] = val;
30
31 // case 2: val (= true)
32 else _map[val] = std::string("true");
33 }
34 }
35
36 //! \brief check keys in the options are in the set keywords.
37 //! \returns vector of erroneous keywords in options.
38 inline std::vector<std::string> validate(const std::set<std::string>& keywords) const
39 {
40 std::vector<std::string> err;
41 for(auto& key : _map)
42 if(!keywords.contains(key.first)) err.push_back(key.first);
43 return err;
44 }
45
46 //! \brief retrieve an option
47 template<typename RET>
48 inline RET get(const std::string& key) const
49 {
50 if(_map.contains(key)) return bbm::fromString<RET>( _map.at(key) );
51 else throw std::runtime_error(std::string("Missing required option ") + key);
52 }
53
54 //! \brief retrieve an option
55 template<typename RET>
56 inline RET get(const std::string& key, const RET& default_value) const
57 {
58 if(_map.contains(key)) return bbm::fromString<RET>( _map.at(key) );
59 else return default_value;
60 }
61
62 private:
63 std::map<std::string, std::string> _map;
64 };
65
66} // end bbm namespace
67
68#endif /* _BBM_OPTION_H_ */
concept to check if a type has a valid string_converter.
std::pair< std::string, std::string > split_eq(const std::string &str)
split a string of the form "key = val" in key and value. If no '=', then return an empty key.
Definition: string_util.h:77
Definition: aggregatebsdf.h:29
constexpr auto default_value(T)
Definition: bsdf_attribute.h:37
Helper method for processing strings.
Definition: option.h:20
std::map< std::string, std::string > _map
Definition: option.h:63
RET get(const std::string &key, const RET &default_value) const
retrieve an option
Definition: option.h:56
RET get(const std::string &key) const
retrieve an option
Definition: option.h:48
option_parser(int argc, char **argv)
Parse the options from the commandline arguments (argc,argv)
Definition: option.h:22
std::vector< std::string > validate(const std::set< std::string > &keywords) const
check keys in the options are in the set keywords.
Definition: option.h:38