| Home | Libraries | People | FAQ | More

##### Optional Generator (`-a`)

###### Description

The optional generator is used to conditionally execute an embedded generator. It succeeds always.

###### Header

    // forwards to <boost/spirit/home/karma/operator/optional.hpp>
    #include <boost/spirit/include/karma_optional.hpp>

Also, see Include Structure.

###### Model of

> `UnaryGenerator`

###### Expression Semantics

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

Expression | Semantics
--- | ---
`-a` | The generator `a` is executed depending on the availability of an attribute. The optional generator succeeds if its embedded generator succeeds (unless the underlying output stream reports an error).

###### Attributes

See Compound Attribute Notation.

Expression | Attribute
--- | ---

`-a` (optional, unary `-`)

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

| Important
The table above uses `optional<A>` as a placeholder only. The notation of `optional<A>` stands for the data type `boost::optional<A>`.

The optional generator will execute its embedded generator once if the provided attribute holds a valid value. It forwards the value held in its attribute to the embedded generator.

It is important to note, that the optional generator does not perform any buffering of the output generated by its embedded elements. That means that any failing element might have already generated some output, which is not rolled back.

| Tip

The simplest way to force a optional generator to behave as if it did buffering is to wrap it into a buffering directive (see `buffer`):

    buffer[-a]

which will not generate any output in case of a failing generator `-a`.

###### Complexity

> The overall complexity of the optional generator is defined by the complexity of its embedded generator. The complexity of the optional generator itself is O(1).

###### Example

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

Some includes:

    #include <boost/spirit/include/karma.hpp>
    #include <boost/spirit/include/support_utree.hpp>
    #include <boost/spirit/include/phoenix_core.hpp>
    #include <boost/spirit/include/phoenix_operator.hpp>
    #include <boost/fusion/include/std_pair.hpp>
    #include <iostream>
    #include <string>

Some using declarations:

    using boost::spirit::karma::double_;

Basic usage of an optional generator:

    boost::optional<double> val(1.0);
    test_generator_attr("1.0", -double_, val);
    test_generator_attr("2.0", -double_, 2.0);

Usage and result of an empty optional generator:

    boost::optional<double> val;          // empty optional
    test_generator_attr("", -double_, val);