Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
Optional Generator (-a)

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

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

Also, see Include Structure.

Model of


Expression Semantics

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




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).


See Compound Attribute Notation.



-a (optional, unary -)

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

[Important] 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] 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):


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


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).

[Note] 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/phoenix/core.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/proto/deep_copy.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);