我如何假设“默认值”?当使用 boost::spirit 解析时?

发布于 2024-08-25 14:48:14 字数 539 浏览 1 评论 0原文

假设我定义了一个语法,如下所示:

some_rule := a b [c [d]]

其中 cd 是可选的,如果未给出,则默认为某个值(假设为 14)。如果未给出该值,我可以将其设置为默认值 14 吗?我希望生成的 std::vector 的大小始终为 4。

我得到的最接近的结果如下:

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。这不仅是严重错误的,而且也不优雅。有更好的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

比忠 2024-09-01 14:48:14

看起来您可以使用 boost::qi::attr 辅助解析器来完成此操作。

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

我仍然不确定这是否是最好的方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文