Generate string if boolean attribute is true (match karma with qi :: match)

Imagine we want to parse and generate a simple C ++ member function declaration using Boost.Spirit.

Qi grammar Qi might look like this:

function_ %= type_ > id_ > "()" > matches["const"];

      

This means that the function const

is stored in bool

.

How to write an appropriate generator with karma?

function_ %= type_ << ' ' << id_ << "()" << XXX[" const"];

      

Here we need a directive that consumes a boolean attribute, executes an inline generator if the attribute true

does nothing. We need something that makes the following tests successful.

test_generator_attr("abc", XXX["abc"], true);
test_generator_attr("", XXX["abc"], false);

      

Is such a directive already available in Boost.Spirit?

+3


source to share


1 answer


The first thing that comes to my mind is

bool const_qualifier = true;

std::cout << karma::format(
      karma::omit[ karma::bool_(true) ] << " const" | "",
      const_qualifier);

      

Feels a little ... awkward. I'll see later what I forgot :)

UPDATE Here's a slightly more elegant usage with 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";
    }   
}

      

Printing

void foo() const 
void foo()  

      

+2


source







All Articles