【发布时间】:2020-03-12 19:16:11
【问题描述】:
Boost Spirit Qi 解析当然是 C++ 的一个独特应用,它具有陡峭的学习曲线。在这种情况下,我试图解析一个字符串,该字符串包含语法正确的 C++ 列表初始化的 struct,其中包含 std::vector 的 std::tuple<std::string, short>。这是struct的声明:
typedef std::vector<std::tuple<std::string, int>> label_t;
struct BulkDataParmas
{
std::string strUUID;
short subcam;
long long pts_beg;
long long pts_len;
long long pts_gap;
label_t labels;
};
这是我将这种结构绑定到 Qi 属性的失败尝试。如果我还注释掉struct 的vector 成员,注释掉的start 将按预期工作。 (我也试过std::pair 而不是std::tuple)。
BOOST_FUSION_ADAPT_STRUCT
(
BulkDataParmas,
(std::string, strUUID)
(short, subcam)
(long long, pts_beg)
(long long, pts_len)
(long long, pts_gap)
(label_t, labels)
)
template <typename Iterator>
struct load_parser : boost::spirit::qi::grammar<Iterator, BulkDataParmas(), boost::spirit::ascii::space_type>
{
load_parser() : load_parser::base_type(start)
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
using qi::attr;
using qi::short_;
using qi::int_;
using qi::long_long;
using qi::lit;
using qi::xdigit;
using qi::lexeme;
using ascii::char_;
using boost::proto::deep_copy;
auto hex2_ = deep_copy(xdigit >> xdigit >> xdigit >> xdigit);
auto hex4_ = deep_copy(hex2_ >> hex2_);
auto hex6_ = deep_copy(hex4_ >> hex2_);
auto fmt_ = deep_copy('"' >> hex4_ >> char_('-') >> hex2_ >> char_('-') >> hex2_ >> char_('-') >> hex2_ >> char_('-') >> hex6_ >> '"');
uuid = qi::as_string[fmt_];
quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'];
label = '{' >> quoted_string >> ',' >> int_ >> '}';
start = '{' >> uuid >> ',' >> short_ >> ',' >> long_long >> ',' >> long_long >> ',' >> long_long >> ',' >> '{' >> -(label >> *(',' >> label)) >>'}' >> '}';
// start = '{' >> uuid >> ',' >> short_ >> ',' >> long_long >> ',' >> long_long >> ',' >> long_long >> '}';
}
private:
boost::spirit::qi::rule<Iterator, std::string()> uuid;
boost::spirit::qi::rule<Iterator, std::string()> quoted_string;
boost::spirit::qi::rule<Iterator, std::string(), boost::spirit::ascii::space_type> label;
boost::spirit::qi::rule<Iterator, BulkDataParmas(), boost::spirit::ascii::space_type> start;
};
这是一个要解析的示例字符串:
"{ \"68965363-2d87-46d4-b05d-f293f2c8403b\", 0, 1583798400000000, 86400000000, 600000000, { { \"motorbike\", 5 }, { \"aeroplane\", 6 } } };"
【问题讨论】:
标签: c++ parsing boost boost-spirit boost-spirit-qi