为使用逗号作为小数分隔符的实数定义strict_real_policies策略
需求可行性结论
这个需求非常容易实现,仅需要少量代码修改即可完成,不需要改动原有strict_real_policies的核心逻辑。
核心实现思路
- 直接继承
boost::spirit::qi::strict_real_policies基类 - 重写
parse_double、parse_float、parse_long_double三个解析方法,核心逻辑为:将输入字符串中的逗号替换为点号后,再调用父类的原生解析逻辑 - 可按需补充额外校验规则,比如禁止输入中出现点号作为千位分隔符,避免
1.234,56这类混合格式解析出错
最简实现代码示例
#include <boost/spirit/include/qi.hpp> #include <algorithm> #include <string> template <typename T> struct comma_separated_real_policies : public boost::spirit::qi::strict_real_policies<T> { template <typename Iterator, typename Attribute> static bool parse_double(Iterator& first, Iterator const& last, Attribute& attr) { std::string input_buf(first, last); std::replace(input_buf.begin(), input_buf.end(), ',', '.'); auto buf_begin = input_buf.begin(); auto buf_end = input_buf.end(); bool parse_success = boost::spirit::qi::strict_real_policies<T>::parse_double(buf_begin, buf_end, attr); if (parse_success) { // 同步原输入迭代器的偏移位置 std::advance(first, std::distance(buf_begin, buf_end)); } return parse_success; } // 按照相同逻辑补充parse_float、parse_long_double方法即可 }; // 使用方式:定义对应real_parser即可 // using comma_real = boost::spirit::qi::real_parser<double, comma_separated_real_policies<double>>;
注意事项
如果你的输入场景带千位分隔符(比如德国格式的
1.234,56对应数值1234.56),只需要在替换逗号之前先预处理删除所有点号即可,不需要改动核心解析逻辑。
内容的提问来源于stack exchange,提问作者Niels Holst
相关产品推荐
相关产品推荐

