C++ 使用容器解析结构

C++ 使用容器解析结构,c++,boost,c++14,boost-spirit,boost-spirit-x3,C++,Boost,C++14,Boost Spirit,Boost Spirit X3,如何使用boost.spirit x3解析为以下结构: struct person{ std::string name; std::vector<std::string> friends; } struct-person{ std::字符串名; 病媒朋友; } 来自boost.spirit v2,我会使用语法,但由于X3不支持语法,我不知道如何做到这一点 编辑:如果有人能帮我编写一个解析字符串列表的解析器,并返回一个person,第一个字符串是名称,字符串的res

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

struct person{
    std::string name;
    std::vector<std::string> friends;
}
struct-person{
std::字符串名;
病媒朋友;
}
来自boost.spirit v2,我会使用语法,但由于X3不支持语法,我不知道如何做到这一点


编辑:如果有人能帮我编写一个解析字符串列表的解析器,并返回一个
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;
}
/#定义BOOST_SPIRIT_X3_调试
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
名称空间x3=boost::spirit::x3;
结构人
{
std::字符串名;
病媒朋友;
};
增强融合适应结构(
人,
(std::字符串,名称)
(std::矢量,朋友)
);
auto const name=x3::规则{“name”}
=x3::raw[x3::lexeme[x3::alpha>>*x3::alnum]];
auto const root=x3::规则{“person”}
=名称>>*名称;
int main(int,char**)
{
std::string const input=“bob john ellie”;
auto it=input.begin();
自动结束=输入。结束();
人p;
if(短语解析(it,end,root>>x3::eoi,x3::space,p))
{

std::cout x3::position_标记的目的是什么?@Exagon我不确定,他们在我遇到的几乎所有示例中都使用它,所以我只是习惯于添加它。我做一些x3已经有一段时间了。就其本身而言,它没有任何作用。您需要在规则标记结构中有额外的操作来实现“面向方面的属性扩展”.事实上,你应该删除基本类。我已将其删除,以避免其他遇到此问题的人感到困惑。