4

我正在尝试使用Boost.Sprit x3将两个整数的序列匹配到std::pair<int, int>. 从文档来看,以下代码应该可以编译:


#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>

int main()
{
    using namespace boost::spirit::x3;

    std::string input("1 2");
    std::pair<int, int> result;
    parse(input.begin(), input.end(), int_ >> int_, result);
}

melpon.org 链接


但是,它只匹配第一个整数。如果我更改std::pair<int, int> result;int result;然后 print result,我会得到1我的输出。

为什么会这样?int_ >> int_定义匹配(并设置为属性)两个整数的解析器的正确方法不是吗?

4

1 回答 1

5

实际上,@TC 的包含注释<boost/fusion/adapted/std_pair.hpp>仅足以使编译器静音,而不能正确解析您的字符串。我还必须更改跳过空格的x3::parse()for a :x3::phrase_parse()

#include <iostream>
#include <string>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/adapted/std_pair.hpp>

int main()
{
    namespace x3 = boost::spirit::x3;

    std::string input("1 2");
    std::pair<int, int> result;
    auto ok = x3::phrase_parse(input.begin(), input.end(), x3::int_ >> x3::int_, x3::space, result);
    std::cout << std::boolalpha << ok << ": ";
    std::cout << result.first << ", " << result.second;
}

现场示例

请注意,我还将您的替换using namespace boost::spirit::x3为命名空间别名x3。这将保持可读性,但会防止将大量 Boost.Spirit 符号转储到您的代码中。

于 2016-08-07T18:15:53.570 回答