Imagine we want to parse and generate simple C++ member function declarations with Boost.Spirit.
The Qi grammar might look like this:
function_ %= type_ > id_ > "()" > matches["const"];
That means, whether the function is const
is stored in a bool
.
How to write the corresponding generator with Karma?
function_ %= type_ << ' ' << id_ << "()" << XXX[" const"];
Here, we want a directive that consumes a boolean attribute, executes the embedded generator if the attribute is true
and does nothing otherwise. We want something that makes the following tests succeed.
test_generator_attr("abc", XXX["abc"], true);
test_generator_attr("", XXX["abc"], false);
Is such a directive already available in Boost.Spirit?
The first thing that enters my mind at the moment is
bool const_qualifier = true;
std::cout << karma::format(
karma::omit[ karma::bool_(true) ] << " const" | "",
const_qualifier);
It feels a bit... clumsy. I'll have a look later what I'm forgetting :)
UPDATE Here's a slightly more elegant take using karma::symbols<>
:
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
int main()
{
karma::symbols<bool, const char*> const_;
const_.add(true, "const")(false, "");
for (bool const_qualifier : { true, false })
{
std::cout << karma::format_delimited("void foo()" << const_, ' ', const_qualifier) << "\n";
}
}
Prints:
void foo() const
void foo()
来源:https://stackoverflow.com/questions/25502777/generate-string-if-boolean-attribute-is-true-karma-counterpart-to-qimatches