c – boost :: optional to bool,在boost :: spirit :: qi语法中

前端之家收集整理的这篇文章主要介绍了c – boost :: optional to bool,在boost :: spirit :: qi语法中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的boost :: spirit语法中,我有以下片段;
implicit_method_declaration = (-(qi::token(ABSTRACT)) >> ...)

– (qi :: token(ABSTRACT)的类型是boost :: optional< boost :: iterator_range< std :: string :: iterator>>但是我只是使用这个构造来检查是否抽象关键字,实际上是现在,也就是说,我宁愿 – (qi :: token(ABSTRACT)的类型为bool,值为boost :: optional< ...> operator bool()const.

我将如何实现这一目标?

解决方法

我想你正在寻找qi :: matches []:
implicit_method_declaration = 
     qi::matches[qi::token(ABSTRACT)] >> ...;

另一种方法是使用qi :: attr()和替代方法

implicit_method_declaration = 
       (
           qi::token(ABSTRACT) >> qi::attr(true) 
         | qi::attr(false)
       ) >> ...;

再次快速演示:http://coliru.stacked-crooked.com/a/ed8bbad53e8c1943

#include <boost/spirit/include/qi.hpp>

namespace qi    = boost::spirit::qi;

template <typename It,typename Skipper = qi::space_type>
    struct parser : qi::grammar<It,bool(),Skipper>
{
    parser() : parser::base_type(implicit_method_declaration)
    {
        using namespace qi;

        implicit_method_declaration = matches["abstract"];

        BOOST_SPIRIT_DEBUG_NODES((implicit_method_declaration));
    }

  private:
    qi::rule<It,Skipper> implicit_method_declaration;
};

bool doParse(const std::string& input)
{
    typedef std::string::const_iterator It;
    auto f(begin(input)),l(end(input));

    parser<It,qi::space_type> p;
    bool data;

    try
    {
        bool ok = qi::phrase_parse(f,l,p,qi::space,data);
        if (ok)   
        {
            std::cout << "parse success\n";
            std::cout << "data: " << data << "\n";
        }
        else      std::cerr << "parse Failed: '" << std::string(f,l) << "'\n";

        if (f!=l) std::cerr << "trailing unparsed: '" << std::string(f,l) << "'\n";
        return ok;
    } catch(const qi::expectation_failure<It>& e)
    {
        std::string frag(e.first,e.last);
        std::cerr << e.what() << "'" << frag << "'\n";
    }

    return false;
}

int main()
{
    doParse("abstract");
    doParse("static final");
}

产量

parse success
data: 1
parse success
data: 0
trailing unparsed: 'static final'
原文链接:https://www.f2er.com/c/119364.html

猜你在找的C&C++相关文章