我怎么可能假设一个“默认值"?使用boost :: spirit解析时? [英] How might I assume a "default value" when parsing using boost::spirit?
问题描述
假设我有一个语法定义如下:
Let's say I have a grammar defined to something like:
some_rule := a b [c [d]]
其中,c
和d
是可选的,如果未指定,则默认为特定值(假设为14).如果未提供该值,我可以将其默认设置为14吗?我希望生成的std::vector
总是大小为4.
where c
, and d
are optional and default to a certain value (let's say 14) if not given. Can I get it to default to the 14 if the value isn't given? I want the produced std::vector
to always be of size 4.
我来的最接近的东西是这样的:
The closest I've come is like the following:
qi::rule<Iterator, std::vector<int>(), ascii::space_type> some_rule;
some_rule %= int_ >> int_ >> -int_ >> -int_;
// ...
some_other_rule = some_rule[&some_callback_for_int_vectors];
然后,对于未显示的可选值,它将获得0(我相信).然后,我将连续的0最终更改为14.这不仅是严重的错误,而且还不够优雅.有更好的方法吗?
which will then get 0 for the optional values that didn't show up (I believe). I then change consecutive 0s at the end into 14. Not only is this horribly wrong, but it's also just not elegant. Is there a better way to do this?
推荐答案
看来您可以使用boost::qi::attr
辅助解析器来做到这一点.
It looks like you can do this with the boost::qi::attr
auxiliary parser.
int default_value = 14;
qi::rule<Iterator, int(), ascii::space_type> some_optional_rule;
qi::rule<Iterator, std::vector<int>(), ascii::space_type> some_rule;
some_optional_rule %= int_ | attr(default_value);
some_rule %= repeat(2)[int_] >> repeat(2)[some_optional_rule];
尽管如此,我仍然不确定这是否是最好的方法.
I'm still not sure if this is the best way to do this though.
这篇关于我怎么可能假设一个“默认值"?使用boost :: spirit解析时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!