使用 boost 精神解析 int 或 double (longest_d)

2021-12-24 00:00:00 c++ boost boost-spirit boost-spirit-qi

我正在寻找一种将字符串解析为 int 或 double 的方法,解析器应该尝试两种选择并选择匹配输入流最长部分的那个.

I'm looking for a way to parse a string as an int or a double, the parser should try both alternatives and choose the one matching the longest portion of the input stream.

有一个已弃用的指令 (longest_d) 完全符合我的要求:

There is a deprecated directive (longest_d) that does exactly what I'm looking for:

number = longest_d[ integer | real ];

...既然已弃用,还有其他选择吗?如果有必要实施语义操作来实现所需的行为,有人有建议吗?

...since it's deprecated, there are any other alternatives? In case it's necessary to implement a semantic action to achieve the desired behavior, does anyone have a suggestion?

推荐答案

首先,切换到 Spirit V2 - 它已经取代了经典精神多年.

Firstly, do switch to Spirit V2 - which has superseded classical spirit for years now.

其次,您需要确保首选 int.默认情况下,double 可以同样好地解析任何整数,因此您需要使用 strict_real_policies 代替:

Second, you need to make sure an int gets preferred. By default, a double can parse any integer equally well, so you need to use strict_real_policies instead:

real_parser<double, strict_real_policies<double>> strict_double;

现在您可以简单地声明

number = strict_double | int_;

  • realpolicies 文档

查看测试程序在 Coliru 上直播

See test program Live on Coliru

#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());
}

相关文章