使用Boost Spirit X3解析逗号分隔的0个或多个列表

3
我经常需要在boost spirit x3中解析逗号分隔的“0或多个列表”。我知道“% - 操作符”能够将“1个或多个列表”解析成“std :: vector”。当我需要一个“0个或多个列表”时,我目前这样做:“-(element_parser % separator)”,它可以实现我的要求,但是解析为“boost :: optional ”,这不完全是我想要的。所以,如何使用boost spirit x3创建一个解析器,将逗号分隔的“0或多个列表”解析为普通的std :: vector?

1
属性是兼容的。试试看。如果你问我,兼容性/转换规则是Spirit库的优势所在。 - sehe
1个回答

4
也许我漏掉了什么,但是在我的测试中使用 - 的效果符合预期:
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/spirit/home/x3.hpp>

namespace x3 = boost::spirit::x3;

const x3::rule<class number_list_tag, std::vector<int>> integer_list = "integer_list";
const auto integer_list_def = -(x3::int_ % ',');
BOOST_SPIRIT_DEFINE(integer_list);

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
    bool first = true;
    os << '[';
    for (const T& x : vec)
    {
        if (first)
            first = false;
        else
            os << ", ";

        os << x;
    }
    os << ']';
    return os;
}

std::vector<int> parse(const std::string& src)
{
    std::vector<int> result;
    auto iter = src.begin();
    bool success = x3::phrase_parse(iter, src.end(), integer_list, x3::space, result);
    if (!success || iter != src.end())
        throw std::runtime_error("Failed to parse");
    else
        return result;
}

int main()
{
    std::cout << "\"\":\t" << parse("") << std::endl;
    std::cout << "\"5\":\t" << parse("5") << std::endl;
    std::cout << "\"1, 2, 3\":\t" << parse("1, 2, 3") << std::endl;
}

输出结果为:

"":     []
"5":    [5]
"1, 2, 3":      [1, 2, 3]

改进后的演示:https://godbolt.org/z/qKoW5Peob - Marek R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接