c++ - 使用 boost Spirit x3 解析为集合

标签 c++ parsing c++14 boost-spirit boost-spirit-x3

我感兴趣的是是否有一种方法可以使用 boostspirit x3 解析成一个集合。背景是我有一串标记,每个标记代表一个枚举值,现在我想创建一个解析器,它解析每个标记是否在字符串中最多出现一次,如果我能得到所有解析的,那将是一个魅力解析时将标记放入 std::set 中。 为了从解析的字符串中获取枚举,我使用了符号表:

enum class foo{bar, baz, bla, huh};

    struct enum_table : x3::symbols<foo> {
        enum_table() {
            add("bar", foo::bar)
                    ("baz", foo::baz)
                    ("huh", foo::huh);
        }
    } const enum_parser;

最佳答案

I am interested in if there is a way to parse into a set using boost spirit x3.

Spirit可以解析为std::set<>开箱即用(至少从 Boost 1.61.0 开始),因此以下内容已经适用于您所显示的类型:

std::set<foo> foos;
x3::phrase_parse(
    input.begin(), input.end(),
    +enum_parser,
    x3::space,
    foos
);

Online Demo

要让解析器在遇到重复项时失败,可以使用 semantic actions 最轻松地完成此操作。 :

std::set<foo> foos;
auto insert_foo_or_fail = [&foos](auto& ctx) {
    _pass(ctx) = foos.insert(_attr(ctx)).second;
};
x3::phrase_parse(
    input.begin(), input.end(),
    +x3::omit[enum_parser[insert_foo_or_fail]],
    x3::space
);

Online Demo

关于c++ - 使用 boost Spirit x3 解析为集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956021/

相关文章:

c++ - 标签分发中的转发参数

c++ - 使用 C++ 函数参数的连续内存保证

c++ - libc 是如何工作的?

parsing - Parsec-Parser 工作正常,但可以做得更好吗?

http - 具有无效上下文的已知 HTTP header

javascript - 切换网站语言 JS/JSON

c++ - 指向成员的指针如何知道它绑定(bind)了哪个成员?

c++ - 以下两个涉及自动返回类型的声明是否相同?如果是这样,为什么?

c++ - 在 Windows 中编译 Faster RNNLM 的问题

c++ - 错误 : ‘chrono’ in namespace ‘std’ does not name a type