gpt4 book ai didi

c++ - boost::bool 可选,在 boost::spirit::qi 语法中

转载 作者:可可西里 更新时间:2023-11-01 18:35:56 25 4
gpt4 key购买 nike

在我的 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, 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'

关于c++ - boost::bool 可选,在 boost::spirit::qi 语法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com