使用容器解析为结构

Parsing into structs with containers

如何使用 boost.spirit x3 解析成如下结构:

struct person{
    std::string name;
    std::vector<std::string> friends;
}

来自 boost.spirit v2 我会使用语法,但由于 X3 不支持语法,我不知道如何做到这一点。

编辑:如果有人能帮我写一个解析字符串列表的解析器就好了,returns第一个字符串的person是名称,字符串的res是在 friends 向量中。

使用 x3 进行解析比使用 v2 简单得多,因此您应该不会遇到太多麻烦。没有语法是件好事!

以下是解析为字符串向量的方法:

//#define BOOST_SPIRIT_X3_DEBUG

#include <fstream>
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>

namespace x3 = boost::spirit::x3;

struct person
{
    std::string name;
    std::vector<std::string> friends;
};

BOOST_FUSION_ADAPT_STRUCT(
    person,
    (std::string, name)
    (std::vector<std::string>, friends)
);

auto const name = x3::rule<struct name_class, std::string> { "name" }
                = x3::raw[x3::lexeme[x3::alpha >> *x3::alnum]];

auto const root = x3::rule<struct person_class, person> { "person" }
                = name >> *name;

int main(int, char**)
{
    std::string const input = "bob john ellie";
    auto it = input.begin();
    auto end = input.end();

    person p;
    if (phrase_parse(it, end, root >> x3::eoi, x3::space, p))
    {
        std::cout << "parse succeeded" << std::endl;
        std::cout << p.name << " has " << p.friends.size() << " friends." << std::endl;
    }
    else
    {
        std::cout << "parse failed" << std::endl;
        if (it != end)
            std::cout << "remaining: " << std::string(it, end) << std::endl;
    }

    return 0;
}

如您所见on Coliru,输出为:

parse succeeded bob has 2 friends.