用容器解析结构

Exa*_*gon 3 c++ boost boost-spirit c++14 boost-spirit-x3

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

struct person{
    std::string name;
    std::vector<std::string> friends;
}
Run Code Online (Sandbox Code Playgroud)

来自boost.spirit v2我会使用语法,但由于X3不支持语法,我不知道如何干净.

编辑:如果有人可以帮我编写一个解析字符串列表的解析器并返回一个person第一个字符串是名称并且字符串的res在friends向量中,那将是很好的.

Bor*_*der 8

使用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;
}
Run Code Online (Sandbox Code Playgroud)

正如你在Coliru上看到的,输出是:

解析成功鲍勃有2个朋友.

  • 就它而言,它没有做任何事情.您需要在规则标记结构中具有额外的操作以具有"面向方面的属性丰富".实际上,你应该删除基类 (3认同)