c++ - 在 boost::spirit::x3 中合成 std​​::pair 属性

标签 c++ boost boost-spirit-x3

<分区>

我正在尝试使用 boost::spirit::x3 创建解析器并偶然发现了一个奇怪的问题。尽管这个特殊用例在 Joel de Guzman 和 Michael Caisse (https://ciere.com/cppnow15/) 的“使用 X3”文档中有所介绍,但并非所有宣传的功能似乎都有效。

问题是 Spirit X3 显然无法合成像 std::pair 这样的元组属性。因此,以下构造声称会产生一个类型为字符串对的属性:

auto item = rule<class item, std::pair<std::string, std::string>>() 
          = name >> ’:’ >> ( quote | name );

简单的例子:

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

using namespace std;

namespace x3 = boost::spirit::x3;

using x3::int_;

int main()
{
    string input = "foo: 146                \n"
                   "the_answer: 42          \n"
                   "freeze_point: 0         \n";

    cout << input << endl << endl;

    auto identifier = x3::rule<class identifier, string>()
            = x3::lexeme[(x3::alpha | '_') >> *(x3::alnum | '_')];

    auto key_value_pair = x3::rule<class key_value_pair, pair<string, int>>()
            = identifier >> ':' >> int_;

    auto first = input.begin();
    auto last = input.end();

    vector<pair<string, int>> output;

    bool result = x3::phrase_parse(first, last, *(key_value_pair), x3::space, output);
    cout << endl << "Result:" << result << endl << (first - input.begin()) << " of " << (last - input.begin());

    return 0;
}

住在 coliru 上: http://coliru.stacked-crooked.com/a/8980ba6215ae0ce7

此代码无法编译,编译器提示试图将一个 int 分配给一个 pair。为什么 Spirit 这样做而不是提取两个值(分别是字符串和整数)并将它们配对?不确定它是否是 boost::spirit::x3 中的错误,也许我做错了什么。

尝试过的编译器:apple-clang、GCC、MSVC17。 Boost 版本为 1.66 或 1.69。

最佳答案

您缺少包含:

#include <boost/fusion/adapted/std_pair.hpp>

include 包含将 std::pair 调整为 boost fusion 序列所需的模板。

关于c++ - 在 boost::spirit::x3 中合成 std​​::pair 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55165674/

相关文章:

c++ - Qt可执行错误-dll库

C++ boost线程在实例化两次时导致段错误

c++ - Spirit V2 和 X3 的状态

c++ - 消除 spirit x3 解析器规则中的左递归

c++ - 我究竟什么时候可以使用期望运算符?

c++ - 为什么保留额外内存时 vector 中的对象没有 move ?

c++ - 虽然循环导致无限循环,但我不知道为什么

c++ - 如何在 SPOJ Feynman 中应用动态规划?

c++ - boost/Netbeans : Recursive Includes Related to BSD on Linux Mint 17. 2

c++ - Boost.Asio : SSL Server and Client. 服务器 SIGSEGV 和客户端短读取错误