Search code examples
c++boost-spiritboost-spirit-qi

How to use the parse/phrase_parse function


Concretely, using the grammar g, how do I parse the string s ? What arguments should I give ? I've tried many calls and always got errors.

Also, since I'm not sure yet which one I will use later, would there be any difference using phrase_parse instead ?

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;
}

Solution

  • Basically, you should look in the tutorial, but part of the issue is, you more or less need to create a variable to hold the start iterator. Because, it is passed by reference to qi::parse, and where exactly it stops can be considered an output of the qi::parse function. If you try to pass it by s.begin() it won't work because then you are trying to bind a reference to a temporary.

    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;
    }
    

    You use phrase_parse only when you want to explicitly specify a skip grammar.