首先,逐个介绍。请参阅下面的开箱即用答案。
问题 1:为什么我必须在上面的规则标志中添加语义操作?
char 不能转换为 std::string 吗?
呃,没有字符不能转换为字符串。其他选项见下文。
问题2:为什么我尝试合并最后两条规则时编译失败
像这样:
rule<Iterator, std::string()> floating = -sign >>
(mantissa >> -(exp | suffix) | +digit >> (exp | suffix));
这是由于原子属性分配的规则。解析器公开了类似
的内容
vector2<optional<string>, variant<
vector2<string, optional<string> >,
vector2<std::vector<char>, optional<string> > >
或类似的(参见the documentation for the parsers,我是从内存中在浏览器中输入的)。显然,这不能分配给字符串。使用qi::as<> 强制进行原子分配。为方便起见***有qi::as_string:
floating = qi::as_string [ -sign >> (mantissa >> -(exp | suffix) |
+digit >> (exp | suffix)) ]
问题3:假设我想让float的属性为double并且
编写一个语义动作来进行从字符串到双精度的转换。我怎样才能
从语义内部引用规则匹配的整个字符串
行动?
您可以再次使用qi::as_string,但最合适的似乎是使用qi::raw:
floating = qi::raw [ -sign >> (mantissa >> -(exp | suffix) |
+digit >> (exp | suffix)) ]
[ _val = parse_float(_1, _2) ];
此解析器指令公开了一对源迭代器,因此您可以使用它来引用匹配的确切输入序列。
问题4:问题2的规则浮动中,占位符_2是什么意思
参考,它的类型是什么?
一般来说,要检测属性类型 - 也就是说,当文档让您感到困惑或者您想仔细检查您对它的理解时 - 请在此处查看答案:
开箱即用
你有没有看使用Qi的builtin real_parser<> template,可以全面定制。看起来您确实想使用它而不是在语义操作中进行自定义解析。
带有策略的real_parser模板既快速又非常灵活和健壮。另请参阅最近的答案Is it possible to read infinity or NaN values using input streams?。
对于 RealPolicies 模型,以下表达式必须有效:
Expression | Semantics
===========================+=============================================================================
RP::allow_leading_dot | Allow leading dot.
RP::allow_trailing_dot | Allow trailing dot.
RP::expect_dot | Require a dot.
RP::parse_sign(f, l) | Parse the prefix sign (e.g. '-'). Return true if successful, otherwise false.
RP::parse_n(f, l, n) | Parse the integer at the left of the decimal point. Return true if successful, otherwise false. If successful, place the result into n.
RP::parse_dot(f, l) | Parse the decimal point. Return true if successful, otherwise false.
RP::parse_frac_n(f, l, n) | Parse the fraction after the decimal point. Return true if successful, otherwise false. If successful, place the result into n.
RP::parse_exp(f, l) | Parse the exponent prefix (e.g. 'e'). Return true if successful, otherwise false.
RP::parse_exp_n(f, l, n) | Parse the actual exponent. Return true if successful, otherwise false. If successful, place the result into n.
RP::parse_nan(f, l, n) | Parse a NaN. Return true if successful, otherwise false. If successful, place the result into n.
RP::parse_inf(f, l, n) | Parse an Inf. Return true if successful, otherwise false. If successful, place the result into n
请参阅 the example,了解如何使用它的令人信服的想法。