我正在寻找一种将字符串解析为 int 或 double 的方法,解析器应该尝试这两种选择并选择与输入流的最长部分匹配的那个。
有一个已弃用的指令 (longest_d) 完全符合我的要求:
number = longest_d[ integer | real ];
...既然它已被弃用,还有其他选择吗?如果有必要实现语义操作来实现所需的行为,有人有什么建议吗?
最佳答案
首先,请切换到 Spirit V2 - 多年来它已经取代了经典 spirit 。
其次,您需要确保首选 int。默认情况下,double 可以很好地解析任何整数,因此您需要改用 strict_real_policies
:
real_parser<double, strict_real_policies<double>> strict_double;
现在你可以简单的声明
number = strict_double | int_;
见
查看测试程序 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());
}
关于c++ - 使用 boost spirit (longest_d) 解析 int 或 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261502/