| Home | Libraries | People | FAQ | More

##### Optional Parser (`-a`)

###### Description

The optional operator, `-a`, is a unary operator that matches its operand zero or one time.

###### Header

    // forwards to <boost/spirit/home/qi/operator/optional.hpp>
    #include <boost/spirit/include/qi_optional.hpp>

Also, see Include Structure.

###### Model of

> `UnaryParser`

Notation

`a`

  A `Parser`

###### Expression Semantics

Semantics of an expression is defined only where it differs from, or is not defined in `UnaryParser`.

Expression | Semantics
--- | ---
`-a` | Match `a` zero or one time.

###### Attributes

See Compound Attribute Notation.

Expression | Attribute
--- | ---

`-a`

    a: A --> -a: optional<A>
    a: Unused --> -a: Unused

###### Complexity

> The complexity is defined by the complexity of the operand, `a`

###### Example

| Note
The test harness for the example(s) below is presented in the Basics Examples section.

Some using declarations:

    using boost::spirit::ascii::char_;
    using boost::spirit::qi::lexeme;
    using boost::spirit::qi::int_;
    using boost::fusion::vector;
    using boost::fusion::at_c;
    using boost::optional;

Parse a person info with name (in quotes) optional age [9] and optional sex, all separated by comma.

    vector<std::string, optional<int>, optional<char> > attr;

    test_phrase_parser_attr(
        "\"James Bond\", M"
      , lexeme['"' >> +(char_ - '"') >> '"']    // name
            >> -(',' >> int_)                   // optional age
            >> -(',' >> char_)                  // optional sex
      , attr);

    // Should print: James Bond,M
    std::cout << at_c<0>(attr);                 // print name
    if (at_c<1>(attr))                          // print optional age
        std::cout << ',' << *at_c<1>(attr);
    if (at_c<2>(attr))                          // print optional sex
        std::cout << ',' << *at_c<2>(attr);
    std::cout << std::endl;

[9] James Bond is shy about his age :-)