PrevUpHomeNext

Hello, Whomever

This is just about the most minimal example of using Boost.Parser that one could write. We take a string from the command line, or "World" if none is given, and then we parse it:

#include <boost/parser/parser.hpp>

#include <iostream>
#include <string>


namespace bp = boost::parser;

int main(int argc, char const * argv[])
{
    std::string input = "World";
    if (1 < argc)
        input = argv[1];

    std::string result;
    bp::parse(input, *bp::char_, result);
    std::cout << "Hello, " << result << "!\n";
}

The expression *bp::char_ is a parser-expression. It uses one of the many parsers that Boost.Parser provides: char_. Like all Boost.Parser parsers, it has certain operations defined on it. In this case, *bp::char_ is using an overloaded operator* as the C++ version of a Kleene star operator. Since C++ has no postfix unary * operator, we have to use the one we have, so it is used as a prefix.

So, *bp::char_ means "any number of characters". In other words, it really cannot fail. Even an empty string will match it.

The parse operation is performed by calling the parse() function, passing the parser as one of the arguments:

bp::parse(input, *bp::char_, result);

The arguments here are: input, the range to parse; *bp::char_, the parser used to do the parse; and result, an out-parameter into which to put the result of the parse. Don't get too caught up on this method of getting the parse result out of parse(); there are multiple ways of doing so, and we'll cover all of them in subsequent sections.

Also, just ignore for now the fact that Boost.Parser somehow figured out that the result type of the *bp::char_ parser is a std::string. There are clear rules for this that we'll cover later.

The effects of this call to parse() is not very interesting — since the parser we gave it cannot ever fail, and because we're placing the output in the same type as the input, it just copies the contents of input to result.


PrevUpHomeNext