标签:style blog class code c tar
最近项目实在是太忙了~
恩 此封装在一般使用频率不大的键值对应配置, 要复杂的结构还是要编写XML对应生成代码工具比较方便和高效
1 #pragma once 2 #include <enable_hashmap.h> 3 #include <string> 4 #include <boost/property_tree/ptree.hpp> 5 #include <boost/property_tree/xml_parser.hpp> 6 #include <boost/lexical_cast.hpp> 7 8 class enable_xml_config 9 { 10 public: 11 enable_xml_config():b_init(false) 12 { 13 } 14 bool init(const std::string& filename) 15 { 16 boost::property_tree::ptree root; 17 try 18 { 19 boost::property_tree::xml_parser::read_xml(filename, pt, boost::property_tree::xml_parser::trim_whitespace); 20 root = pt.get_child("root"); 21 filepath = filename; 22 } 23 catch (...) 24 { 25 return false; 26 } 27 value_map.clear(); 28 for (auto itr = root.begin(); itr!=root.end(); ++itr) 29 { 30 value_map.insert(std::make_pair(itr->first, itr->second.data())); 31 } 32 b_init = true; 33 return b_init; 34 } 35 36 bool check(const std::string& skey) { 37 auto it = value_map.find(skey); 38 if(it == value_map.end()) 39 return false; 40 return true; 41 } 42 43 template<class T> 44 T get(const std::string& skey) { 45 try 46 { 47 if(check(skey)) 48 return boost::lexical_cast<T>(value_map[skey]); 49 } 50 catch (...) 51 { 52 } 53 return T(); 54 } 55 56 template<class T> 57 T get_ex(const std::string& skey, T& def_val = T()) { 58 try 59 { 60 if(check(skey)) 61 return boost::lexical_cast<T>(value_map[skey]); 62 } 63 catch (...) 64 { 65 } 66 return def_val; 67 } 68 69 bool save() 70 { 71 if(!b_init) 72 return false; 73 74 try 75 { 76 boost::property_tree::ptree& root = pt.get_child("root"); 77 for (auto itr = root.begin(); itr!=root.end(); ++itr) 78 { 79 auto it = value_map.find(itr->first); 80 if (it != value_map.end()) 81 { 82 itr->second.data() = it->second; 83 } 84 } 85 boost::property_tree::xml_writer_settings<char> settings(‘\t‘, 1); 86 boost::property_tree::xml_parser::write_xml(filepath, pt,std::locale(), settings); 87 } 88 catch (...) 89 { 90 return false; 91 } 92 93 return true; 94 } 95 private: 96 ENABLE_MAP<std::string, std::string> value_map; 97 boost::property_tree::ptree pt; 98 std::string filepath; 99 bool b_init; 100 };
附带:
1 #pragma once 2 #ifdef _DEBUG 3 #include <map> 4 #define ENABLE_MAP std::map 5 #else 6 //效率比map高很多 但是无法查看数据 并且无序 7 #include <boost/unordered_map.hpp> 8 #define ENABLE_MAP boost::unordered_map 9 #endif
标签:style blog class code c tar
原文地址:http://www.cnblogs.com/zhangchengxin/p/3733950.html