我正在寻找一种将字符串解析为 int 或 double 的方法,解析器应该尝试两种选择,并选择与输入流的最长部分匹配的一个。
有一个已弃用的指令(longest_d)正是我正在寻找的:
number = longest_d[ integer | real ];
...既然它已被弃用,还有其他替代方案吗?如果有必要实现语义操作来实现所需的行为,有人有建议吗?
首先,请切换到 Spirit V2 - 已取代古典多年来的精神。
其次,您需要确保 int 得到优先选择。默认情况下,双精度数可以同样好地解析任何整数,因此您需要使用strict_real_policies
反而:
real_parser<double, strict_real_policies<double>> strict_double;
现在你可以简单地声明
number = strict_double | int_;
See
- 真实政策文件 http://www.boost.org/doc/libs/1_52_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html#spirit.qi.reference.numeric.real._code__phrase_role__identifier__realpolicies__phrase___code_
查看测试程序住在科利鲁 http://coliru.stacked-crooked.com/a/07c40aa42b49ca05
#include <boost/spirit/include/qi.hpp>
using namespace boost::spirit::qi;
using A = boost::variant<int, double>;
static real_parser<double, strict_real_policies<double>> const strict_double;
A parse(std::string const& s)
{
typedef std::string::const_iterator It;
It f(begin(s)), l(end(s));
static rule<It, A()> const p = strict_double | int_;
A a;
assert(parse(f,l,p,a));
return a;
}
int main()
{
assert(0 == parse("42").which());
assert(0 == parse("-42").which());
assert(0 == parse("+42").which());
assert(1 == parse("42.").which());
assert(1 == parse("0.").which());
assert(1 == parse(".0").which());
assert(1 == parse("0.0").which());
assert(1 == parse("1e1").which());
assert(1 == parse("1e+1").which());
assert(1 == parse("1e-1").which());
assert(1 == parse("-1e1").which());
assert(1 == parse("-1e+1").which());
assert(1 == parse("-1e-1").which());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)