Recursive x3 parser with results passing around

a 夏天 提交于 2019-12-06 07:41:42

You can use x3::with<>.

However, I'd just write this:

auto const block_def =
    '{' >> *( block  | (char_ - '}')) >> '}'
  | '[' >> *( block  | (char_ - ']')) >> ']';

Demo

Live On Coliru

#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace Parser {
    using namespace boost::spirit::x3;

    rule<struct idBlock1> const block {"Block"};
    auto const block_def =
        '{' >> *( block  | (char_ - '}')) >> '}'
      | '[' >> *( block  | (char_ - ']')) >> ']';

    BOOST_SPIRIT_DEFINE(block)
}

int main() {
    std::string const input = R"({
    Some text.
    [
        {
            Some more text.
        }
        Some Text again.
        []
    ]
})";

    std::cout << "Parsed: " << std::boolalpha << parse(input.begin(), input.end(), Parser::block) << "\n";
}

Prints:

Parsed: true

BUT - Code Duplication!

If you insist on generalizing:

auto dyna_block = [](auto open, auto close) {
    return open >> *(block | (char_ - close)) >> close;
};

auto const block_def =
    dyna_block('{', '}')
  | dyna_block('[', ']');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!