如何使用parse/phrase_parse函数

How to use the parse/phrase_parse function

本文关键字:parse 函数 phrase 何使用      更新时间:2023-10-16

具体来说,使用语法g,我如何解析字符串s ?我应该给出什么论据呢?我试了很多次电话,总是出错。

另外,由于我还不确定以后要使用哪一个,使用phrase_parse会有什么不同吗?

namespace qi = boost::spirit::qi;
int main() {
    My_grammar<std::string::const_iterator> g;
    std::string s = "a"; // string to parse
    if (qi::parse( /*...*/ )) {
        std::cout << "String parsed !";
    } else {
        std::cout << "String doesn't parse !";
    }
    return EXIT_SUCCESS;
}

基本上,您应该查看教程,但问题的一部分是,您或多或少需要创建一个变量来保存开始迭代器。因为,它是通过对qi::parse的引用传递的,并且它停止的确切位置可以被认为是qi::parse函数的输出。如果您试图通过s.begin()传递它,它将不起作用,因为您试图将引用绑定到临时对象。

namespace qi = boost::spirit::qi;
int main() {
    My_grammar<std::string::const_iterator> g;
    std::string s = "a"; // string to parse
    std::string::const_iterator it = s.begin(); // The type declaration here
    std::string::const_iterator end = s.end(); // and here needs to match template parameter
                                               // which you used to instantiate g
    if (qi::parse( it, end, g )) {
        std::cout << "String parsed !";
    } else {
        std::cout << "String doesn't parse !";
    }
    return EXIT_SUCCESS;
}

仅当您想显式指定跳过语法时才使用phrase_parse

是有区别的。

phrase_parse使用一个skipper,可能不会消耗所有的输入,仍然返回true。

在所有其他方面,两者是相同的。你应该直接点击文档:

  • http://www.boost.org/doc/libs/1_59_0/libs/spirit/doc/html/spirit/qi/reference/parse_api/iterator_api.html
 std::string::const_iterator f(s.begin(), l(s.end());
 if (qi::parse(f, l, g/*, optional, bound, attribute, references*/))