我正在使用Spirit解析器来解析id 1234
之类的字符串。它与内联start = qi::lit("id") >> qi::int_;
完美配合,但如果我想将它放入一个单独的基于qi :: grammar的结构中则不行。请参阅以下示例中的案例1,2和3:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iostream>
#include <fstream>
namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
struct Context{};
template <typename Iterator, typename SkipParser>
struct IdGrammar : qi::grammar<Iterator, SkipParser>
{
explicit IdGrammar(Context& out) : IdGrammar::base_type(start, "IdGrammar")
{
start = qi::lit("id") >> qi::int_;
}
qi::rule<Iterator, SkipParser> start;
};
template <typename Iterator, typename SkipParser>
struct MyGrammar : qi::grammar<Iterator, SkipParser>
{
explicit MyGrammar(Context& out)
: MyGrammar::base_type(start, "MyGrammar")
{
IdGrammar<Iterator, SkipParser> idGrammar(out);
// start = idGrammar >> *(',' >> idGrammar); // 1 = Parsing fails
start = idGrammar; // 2 = Parsing fails
// start = qi::lit("id") >> qi::int_; // 3 = Parsing succeeds
start.name("the start");
qi::on_error<qi::fail>(
start,
phoenix::ref(std::cout) << phoenix::val("Parsing error: expecting ") << qi::_4 // what failed?
<< phoenix::val(" here: \"")
<< phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
<< phoenix::val("\"")
<< std::endl);
}
qi::rule<Iterator, SkipParser> start;
};
int main()
{
typedef std::string::const_iterator iterator_type;
Context ctx;
MyGrammar<iterator_type, qi::space_type> roman_parser(ctx); // Our grammar
std::string str = "id 5012";
iterator_type iter = str.begin(), end = str.end();
bool r = phrase_parse(iter, end, roman_parser, qi::space);
if (r && iter == end)
{
std::cout << "Parsing succeeded\n";
}
else
{
std::string rest(iter, end);
std::cout << "Parsing failed\n";
std::cout << "stopped at: \"" << rest << "\"\n";
}
}
失败案例(1和2)的输出是:
Parsing failed
stopped at: "id 5012"
这有什么不同?请注意,我删除了整数结果的任何赋值,以保持示例最小 - 假设与问题无关。
答案 0 :(得分:1)
idGrammar
的生命周期必须长于构造函数范围。
使其成为成员变量:
template <typename Iterator, typename SkipParser>
struct MyGrammar : qi::grammar<Iterator, SkipParser>
{
explicit MyGrammar(Context& out)
: MyGrammar::base_type(start, "MyGrammar")
, idGrammar(out)
{
start = idGrammar >> *(',' >> idGrammar); // 1 = Now parsing succeeds
// start = idGrammar; // 2 = Now parsing succeeds
// start = qi::lit("id") >> qi::int_; // 3 = Parsing succeeds
start.name("the start");
qi::on_error<qi::fail>(
start,
phoenix::ref(std::cout) << phoenix::val("Parsing error: expecting ") << qi::_4 // what failed?
<< phoenix::val(" here: \"")
<< phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
<< phoenix::val("\"")
<< std::endl);
}
qi::rule<Iterator, SkipParser> start;
IdGrammar<Iterator, SkipParser> idGrammar;
};