...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
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.
Semantics of an expression is defined only where it differs from, or
is not defined in UnaryGenerator
.
Expression |
Semantics |
---|---|
|
The generator |
See Compound Attribute Notation.
Expression |
Attribute |
---|---|
|
a: A --> -a: optional<A> a: Unused --> -a: Unused
|
Important | |
---|---|
The table above uses |
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[-a]
which will not generate any output in case of
a failing generator |
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 | |
---|---|
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);