Generate string if boolean attribute is true (karma counterpart to qi::matches)

≯℡__Kan透↙ 提交于 2020-01-13 18:55:10

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!