【发布时间】:2014-12-24 16:03:42
【问题描述】:
我正在尝试使用 Boost::Spirit 解析带有转义序列的带引号的字符串。不幸的是,似乎在语法定义中包含引号会导致大量(无用的)编译时错误(正如人们对 Boost 所期望的那样)。省略引号可以让程序编译,但显然它不会像预期的那样运行。这是代码(实际上是大图的一部分,但它说明了问题):
#include "boost/spirit/include/qi.hpp"
#include "boost/proto/deep_copy.hpp"
#include "boost/optional.hpp"
#include <string>
using boost::spirit::qi::char_;
using boost::spirit::qi::lexeme;
using boost::proto::deep_copy;
auto string_literal = deep_copy(
lexeme[
// char_('"')
/* >> */ *((char_ - '"' - '\\') | (char_('\\') >> char_))
// >> char_('"')
]);
template <class Iterator, class Grammar>
boost::optional<std::string> parse_string(Iterator first, Iterator last, Grammar&& gr)
{
using boost::spirit::qi::space;
using boost::spirit::qi::phrase_parse;
std::string temp;
bool success = phrase_parse(
first,
last,
gr,
space,
temp
);
if (first == last && success)
return temp;
else return boost::none;
}
int main()
{
std::string str;
std::cout << "string_literal: ";
getline(std::cin, str);
auto presult = parse_string(str.begin(), str.end(), string_literal);
if (presult) {
std::cout << "parsed: " << *presult;
} else
std::cout << "failure\n";
return 0;
}
取消注释string_literal 定义的注释部分会导致错误。在其当前状态(使用 cmets),代码编译。我尝试了几件事,例如将引号移动到parse_string,以及使用不太具体的定义(上面的定义是我能想到的最不具体的,它仍然有用,正确的语法在@987654321 @,但我想我可以单独验证转义序列),但没有任何效果。
我的 Boost 版本是 1.56.0,我的编译器是 MinGW-w64 g++ 4.9.1。任何帮助都非常感谢。
【问题讨论】:
标签: c++ parsing boost boost-spirit