瀏覽代碼

#utils添加字符串转换成其他类型

zxs 4 天之前
父節點
當前提交
884dd0bec7
共有 1 個文件被更改,包括 20 次插入4 次删除
  1. 20 4
      robot/robotics/utils.hpp

+ 20 - 4
robot/robotics/utils.hpp

@@ -26,6 +26,7 @@
 #include <boost/locale.hpp>
 #include <boost/uuid/uuid.hpp>
 #include <boost/uuid/uuid_io.hpp>
+#include <boost/lexical_cast.hpp>
 #include <boost/algorithm/hex.hpp>
 #include <boost/locale/encoding.hpp>
 #include <boost/uuid/detail/md5.hpp>
@@ -118,12 +119,27 @@ namespace robotics {
 					throw std::runtime_error("转换类型错误");
 				}
 			}
+			/**
+			 * @brief 将字符串转换为指定类型,如果转换失败则返回默认值。
+			 * @tparam _Ret 要转换成的目标类型。
+			 * @param arg 要转换的字符串。
+			 * @param def_value 转换失败时返回的默认值,默认为类型的默认构造值。
+			 * @return 转换成功时返回目标类型的值,否则返回默认值。
+			 */
+			template<typename _Ret>
+			inline _Ret convert(std::string const& arg, _Ret const& def_value = _Ret()) {
+				_Ret result = _Ret();
+				if (!boost::conversion::try_lexical_convert<_Ret>(arg, result)) {
+					return def_value;
+				}
+				return result;
+			}
 			/**
 			 * @brief 格式化输出
-			 * @tparam ..._Args
-			 * @param fmt
-			 * @param ...args
-			 * @return
+			 * @tparam ..._Args 
+			 * @param fmt 
+			 * @param ...args 
+			 * @return 
 			 */
 			template<typename... _Args>
 			inline std::string format(std::string const& fmt, _Args const& ...args) {