Generator Semantic Actions

It gets natural using an attribute to feed Boost Spirit Karma, but we can use semantic actions too.

Karma calls a semantic action before the generator is invoked, giving the action a way of providing data to the generator. So, for a double_ generator, the relative action should be in the form
void F(double& n);
As we have seen for parser semantic action, also generator semantic actions should be designed to support other two parameter (a reference to a Context object and to a boolean). In case of action implemented as function we could simply forget about them, Karma is smart enough to let that working by itself. But for functor and standard lambda we have to explicitly mention them as unused_type parameters.

To use an action that generates an integer, like this one:
void readInt(int& i) { i = 42; }
We call karma::generate() in this way:
using boost::spirit::karma::generate;
using boost::spirit::karma::int_;

std::string generated;
std::back_insert_iterator<std::string> sink(generated);
generate(sink, '{' << int_[&readInt] << '}');
std::cout << "Simple function: " << generated << std::endl;

As a result, the generated string should contain 42 between curly braces.

Have a look at the original Boost Spirit Karma documentation for more details. Here is a C++ source file from there with more examples on generator semantic actions.

No comments:

Post a Comment