【问题标题】:Parsing into structs with containers用容器解析成结构
【发布时间】:2016-05-24 19:28:18
【问题描述】:

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    使用 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,输出为:

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

    【讨论】:

    • x3::position_tagged 的​​用途是什么?
    • @Exagon 我不确定,他们几乎在我遇到的所有示例中都使用它,所以我只是习惯于添加它。自从我做了一些 x3 已经有一段时间了。
    • 就其本身而言,它不会做任何事情。您需要在规则标记结构中进行额外的操作才能具有“面向方面的属性丰富”。实际上,您应该删除基类
    • 我已将其删除以避免其他遇到此问题的人感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多