config.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. *
  3. * @file config.hpp
  4. * @author zxw
  5. * Copyright 2024, yjrobotics. All rights reserved.
  6. *
  7. * robotics
  8. *
  9. */
  10. #pragma once
  11. //boost
  12. #include <boost/format.hpp>
  13. #include <boost/property_tree/ptree.hpp>
  14. #include <boost/property_tree/ini_parser.hpp>
  15. namespace robotics {
  16. namespace v3 {
  17. class config {
  18. public:
  19. /**
  20. * @brief 读取配置文件
  21. * @tparam 返回值类型
  22. * @param 配置段名称
  23. * @param 配置键名称
  24. * @param 默认值
  25. * @param 文件名称
  26. * @return 返回值
  27. */
  28. template<typename _Ret>
  29. static _Ret read(std::string const& section, std::string const& key, _Ret dc = _Ret(), std::string const& filename = "./config/config.ini") {
  30. boost::property_tree::ptree pt;
  31. try {
  32. boost::property_tree::ini_parser::read_ini(filename, pt);
  33. dc = pt.get<_Ret>(section + "." + key, dc);
  34. }
  35. catch (...) {}
  36. return dc;
  37. }
  38. /**
  39. * @brief 读取配置文件
  40. * @param 配置段名称
  41. * @param 配置键名称
  42. * @param 默认值
  43. * @param 文件名称
  44. * @return 返回值
  45. */
  46. static std::string read(std::string const& section, std::string const& key, const char* dc = "", std::string const& filename = "./config/config.ini") {
  47. return read<std::string>(section, key, dc, filename);
  48. }
  49. /**
  50. * @brief 写配置文件
  51. * @tparam 值类型
  52. * @param 返回值类型
  53. * @param 配置段名称
  54. * @param 配置值
  55. * @param 文件名称
  56. */
  57. template<typename _Value>
  58. static void write(std::string const& section, std::string const& key, _Value const& value, std::string const& filename = "./config/config.ini") {
  59. try {
  60. boost::property_tree::ptree pt;
  61. boost::property_tree::ini_parser::read_ini(filename, pt);
  62. pt.put(section + "." + key, boost::str(boost::format("%1%") % value));
  63. boost::property_tree::ini_parser::write_ini(filename, pt);
  64. }
  65. catch (...) {
  66. }
  67. }
  68. };
  69. }
  70. }