KSS Utility
C++ general utilities
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends
attributes.hpp
Go to the documentation of this file.
1 //
2 // attributes.hpp
3 // kssutil
4 //
5 // Created by Steven W. Klassen on 2018-06-15.
6 // Copyright © 2018 Klassen Software Solutions. All rights reserved.
7 // Licensing follows the MIT License.
8 //
9 
15 #ifndef kssutil_attributes_hpp
16 #define kssutil_attributes_hpp
17 
18 #include <map>
19 #include <stdexcept>
20 #include <string>
21 #include <vector>
22 
23 #include "convert.hpp"
24 
25 namespace kss { namespace util {
26 
33  class Attributes {
34  public:
35  using attribute_map_t = std::map<std::string, std::string>;
36 
37  virtual ~Attributes() = default;
38 
44  void setAttribute(const std::string& key, const std::string& value);
45 
51  template <class T>
52  T attribute(const std::string& key) const {
53  const auto ra = rawAttribute(key);
54  return strings::convert<T>(ra);
55  }
56 
62  template <class T>
63  inline T attributeWithDefault(const std::string& key,
64  const T& defaultValue = T()) const
65  {
66  return (hasAttribute(key) ? attribute<T>(key) : defaultValue);
67  }
68 
73  bool hasAttribute(const std::string& key) const;
74 
78  inline const attribute_map_t& attributes() const noexcept {
79  return _attributes;
80  }
81 
86  std::vector<std::string> attributeKeys() const;
87 
88  protected:
89  Attributes() = default;
90  Attributes(const Attributes&) = default;
91  Attributes(Attributes&&) = default;
92  Attributes& operator=(const Attributes&) = default;
93  Attributes& operator=(Attributes&&) = default;
94 
99  std::string rawAttribute(const std::string& key) const;
100 
104  attribute_map_t& attributes() noexcept { return _attributes; }
105 
106  private:
107  attribute_map_t _attributes;
108  };
109 }}
110 
111 #endif
std::map< std::string, std::string > attribute_map_t
Definition: attributes.hpp:35
std::vector< std::string > attributeKeys() const
virtual ~Attributes()=default
attribute_map_t & attributes() noexcept
Definition: attributes.hpp:104
Adds an attribures API to subclasses.
Definition: attributes.hpp:33
bool hasAttribute(const std::string &key) const
Convert strings to other types.
const attribute_map_t & attributes() const noexcept
Definition: attributes.hpp:78
std::string rawAttribute(const std::string &key) const
Attributes & operator=(const Attributes &)=default
void setAttribute(const std::string &key, const std::string &value)
T attributeWithDefault(const std::string &key, const T &defaultValue=T()) const
Definition: attributes.hpp:63
T attribute(const std::string &key) const
Definition: attributes.hpp:52