Xirema

Recursive Map

Sep 27th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<map>
  4. #include<vector>
  5. #include<boost/variant.hpp>
  6. #include<boost/variant/get.hpp>
  7. #include<boost/optional.hpp>
  8. #include<boost/none.hpp>
  9.  
  10. class recursive_map {
  11.     class recursive_map_impl {
  12.         std::map<std::string, boost::variant<boost::blank, std::string, recursive_map_impl>> map;
  13.  
  14.         bool set_value(std::string val, std::string key) {
  15.             map[key] = val;
  16.             return true;
  17.         }
  18.  
  19.         template<typename... T>
  20.         bool set_value(std::string val, std::string key, T... mappings) {
  21.             if (boost::get<boost::blank>(&map[key])) map[key] = recursive_map_impl{};
  22.             if (recursive_map_impl * sub_map = boost::get<recursive_map_impl>(&(map[key]))) {
  23.                 return sub_map->set_value(val, mappings...);
  24.             }
  25.             return false;
  26.         }
  27.  
  28.         boost::optional<std::string> get_value(const std::string & key) {
  29.             if (std::string * sub_string = boost::get<std::string>(&map[key])) {
  30.                 return boost::make_optional<std::string>(*sub_string);
  31.             } else {
  32.                 return boost::none;
  33.             }
  34.         }
  35.  
  36.         template<typename... T>
  37.         boost::optional<std::string> get_value(const std::string & key, T... mappings) {
  38.             if (recursive_map_impl * sub_map = boost::get<recursive_map_impl>(&(map[key]))) {
  39.                 return sub_map->get_value(mappings...);
  40.             }
  41.             else {
  42.                 return boost::none;
  43.             }
  44.         }
  45.         friend class recursive_map;
  46.     };
  47.  
  48.     recursive_map_impl map;
  49.  
  50. public:
  51.     template<typename... T>
  52.     auto set_value(std::string value, T... mappings) {
  53.         return map.set_value(value, mappings...);
  54.     }
  55.  
  56.     template<typename... T>
  57.     auto get_value(T... mappings) {
  58.         return map.get_value(mappings...);
  59.     }
  60. };
Add Comment
Please, Sign In to add comment