开发者

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

开发者 https://www.devze.com 2022-12-23 08:16 出处:网络
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 t

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 bet开发者_C百科ter way to do this?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消