boost ::可选bool,里面boost :: spirit :: qi语法 [英] boost::optional to bool, inside boost::spirit::qi grammar
问题描述
在我的 boost :: spirit
语法我有以下代码片段:
In my boost::spirit
grammar I have the following snippet;
implicit_method_declaration = (-(qi::token(ABSTRACT)) >> ...)
- (qi :: token(ABSTRACT)
的类型是 boost :: optional< boost :: iterator_range< std :: string: :iterator>>
但是我只使用这个结构来检查抽象关键字是否真的存在,也就是说,我宁愿有 - (qi ::令牌(ABSTRACT)
的类型为 bool
,值为 boost :: optional< ...& )const
。
The type of -(qi::token(ABSTRACT)
is boost::optional<boost::iterator_range<std::string::iterator>>
however I'm only using this construct to check if the abstract keyword, is actually present, that is, I'd rather have -(qi::token(ABSTRACT)
have the type bool
with the value boost::optional<...> operator bool() const
.
如何实现这一目标?
推荐答案
我认为你正在寻找 qi :: matches []
:
implicit_method_declaration =
qi::matches[qi::token(ABSTRACT)] >> ...;
另一种方法是使用 qi :: attr()
替换:
An alternative would be to use qi::attr()
with alternatives:
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, bool(), 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'
这篇关于boost ::可选bool,里面boost :: spirit :: qi语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!