|
| 1 | +#ifndef LIBRESPONSE_CONFIGURABLE_H_ |
| 2 | +#define LIBRESPONSE_CONFIGURABLE_H_ |
| 3 | + |
| 4 | +/*! |
| 5 | + * @file |
| 6 | + * |
| 7 | + * Inheritable configuration by wrapping a string->string map. |
| 8 | + */ |
| 9 | + |
| 10 | +#include <cstdlib> |
| 11 | +#include <map> |
| 12 | +#include <sstream> |
| 13 | +#include <string> |
| 14 | +#include <stdexcept> |
| 15 | + |
| 16 | +typedef std::map< std::string, std::string > ssmap; |
| 17 | +typedef ssmap::const_iterator ssmap_it_type; |
| 18 | + |
| 19 | +namespace libresponse { |
| 20 | + |
| 21 | +/*! |
| 22 | + * Inheritable configuration by wrapping a string->string map. |
| 23 | + */ |
| 24 | +class configurable { |
| 25 | +private: |
| 26 | + ssmap m_params; //!< Key-value parameters |
| 27 | + std::string m_empty; //!< Empty value |
| 28 | + |
| 29 | +public: |
| 30 | + /*! |
| 31 | + * Default constructor |
| 32 | + */ |
| 33 | + configurable() { } |
| 34 | + |
| 35 | + const std::string &get_param(const std::string &key) const; |
| 36 | + void cfg(const std::string &key, const std::string &val); |
| 37 | + |
| 38 | + template<typename T> |
| 39 | + void get_param(const std::string &key, T &val) const; |
| 40 | + |
| 41 | + template<typename T> |
| 42 | + T get_param(const std::string &key) const; |
| 43 | + |
| 44 | + template<typename T> |
| 45 | + void cfg(const std::string &key, const T &val); |
| 46 | + |
| 47 | + /*! |
| 48 | + * Print all key-value pairs to stdout |
| 49 | + */ |
| 50 | + void dump_params() const; |
| 51 | + |
| 52 | + bool has_param(const std::string &key) const; |
| 53 | +}; |
| 54 | + |
| 55 | + |
| 56 | +template<typename T> |
| 57 | +void configurable::cfg(const std::string &key, const T &val) { |
| 58 | + |
| 59 | + std::ostringstream ss; |
| 60 | + ss << val; |
| 61 | + cfg(key, ss.str()); |
| 62 | +} |
| 63 | + |
| 64 | + |
| 65 | +template<typename T> |
| 66 | +void configurable::get_param(const std::string &key, T &val) const { |
| 67 | + |
| 68 | + const std::string &par = get_param(key); |
| 69 | + if (!par.empty()) { |
| 70 | + std::stringstream ss; |
| 71 | + ss << par; ss >> val; |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | + |
| 76 | +template<typename T> |
| 77 | +T configurable::get_param(const std::string &key) const { |
| 78 | + |
| 79 | + if(m_params.count(key) == 0) { |
| 80 | + throw std::logic_error( |
| 81 | + "configurable::get_param(): no parameter with given name: " + key); |
| 82 | + } |
| 83 | + |
| 84 | + T t; |
| 85 | + get_param(key, t); |
| 86 | + return t; |
| 87 | +} |
| 88 | + |
| 89 | +} // namespace libresponse |
| 90 | + |
| 91 | +#endif // LIBRESPONSE_CONFIGURABLE_H_ |
0 commit comments