boostboost-spiritboost-spirit-karma

Boost Spirit Karma equivalent to Qi matches


What is the equivalent to boost::spirit::qi::matches in boost::spirit::karma? For example I want to generate a literal "array" only if a boolean flag is set true.


Solution

  • Use the specified value form of bool_ to consume the attribute only if it matches the supplied value:

    Live On Coliru

    #include <boost/spirit/include/karma.hpp>
    
    namespace karma = boost::spirit::karma;
    
    int main() {
        using namespace karma;
    
        for (int i = 0; i < 10; ++i)
        {
            bool b = (0 == i%3);
            std::cout << format_delimited(
                    (omit[bool_(true)] << "array" | omit[bool_(false) << "vector"]),
                    ';',
                    b
                ) << "\n";
        }
    
    }
    

    Prints

    array;
    
    
    array;
    
    
    array;
    
    
    array;