<分区>
我正在尝试使用 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。