How might I assume a “default value” when parsing using boost::spirit?

微笑、不失礼 提交于 2019-12-07 16:19:57

问题


Let's say I have a grammar defined to something like:

some_rule := a b [c [d]]

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];

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?


回答1:


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.



来源:https://stackoverflow.com/questions/2460376/how-might-i-assume-a-default-value-when-parsing-using-boostspirit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!