Reference Wrappers (ref)

We can directly extract the parser result and place that in a variable using this predefined semantic action functor. The class reference_ wrapper wraps a reference to a variable of type T. The reference_wrapper handles the semantic action construct:

 expr[ref(var)]

where expr is an expression that evaluates to a parser and var is a variable that will hold the parsed result. A reference_wrapper object is not created directly. Instead, a reference_wrapper generator ref is responsible for its creation. The expression:

 ref(var)

creates a reference_wrapper given a reference to a container. The reference_wrapper acts like a functor that is compatible with the semantic action that expects the interface:

void operator()(IteratorT begin, IteratorT end);

When this operator is invoked, the reference_wrapper expects that the referenced object is:

a container of some sort (e.g. std::string, std::vector)
that it may be constructed given two iterators
has a member function swap, that swaps the contents of two containers.

Here is an example that extracts the parsed result and puts it a string:

std::string s;          // will hold the parsed data
r = (+anychar)[ref(s)]; // if successful, will write the parsed result into the string

The reference_wrapper also has an alternative functor interface:

void operator()(T val);

This alternate interface may be used by specialized actions. When this operator is invoked, the reference_wrapper merely expects that the referenced object be assignable (has an assignment operator). Here is an example that extracts complex numbers of the form r or (r) or (r, i):

double r = 0;
double i = 0;
rule<> complex_parser;

complex_parser = real_p[ref(r)]
    |   '(' >> real_p[ref(r)] >> !(',' >> real_p[ref(i)]) >> ')';