提升::精神:基本"logical and"表达式解析

Boost::Spirit : Basic "logical and" expression parsing

本文关键字:表达式 and logical 基本 提升 精神      更新时间:2023-10-16

我正在尝试学习Boost::Spirit的基础知识,但进展不顺利。我正在尝试解析用 c++ 语法编写的简单"逻辑和"表达式。由于某种原因,我无法让空间跳跃工作。

这是我到目前为止的代码

template <typename Iterator>
struct boolGrammar : public qi::grammar<Iterator, bool>
{
public:
    boolGrammar() : boolGrammar::base_type(expression)
    {
        andExpr = (qi::lit(L"1") >> qi::lit(L"&&") >> qi::lit(L"1"))[qi::_val = true];
    }
    qi::rule<Iterator, bool> andExpr;
};
bool conditionEvalAndParse(std::wstring condition)
{
    boolGrammar<std::wstring::iterator> g;
    bool result = false;
    std::wstring::iterator it = condition.begin();
    bool parseResult = qi::phrase_parse(it, condition.end(), g, boost::spirit::standard_wide::space , result);
    if (parseResult) {
        return result;
    }
    else
    {
        std::wcout << L"Failed to parse condition " << condition << L". The following wasn't parsed : " << std::wstring(condition, it - condition.begin(), std::wstring::npos) << std::endl;
        return false;
    }
}

在我的测试代码中,我调用:

conditionEvalAndParse(L"1&&1");
conditionEvalAndParse(L"1 && 1");

果然,我得到了一个可爱的控制台输出:

"Failed to parse condition 1 && 1. The following wasn't parsed : 1 && 1"

有人愿意指出新手的错误吗? :)

通过将船长添加为模板参数来解决,如@Richard Hodges前面的问题所示:

template <typename Iterator, typename Skipper = boost::spirit::standard_wide::space_type>
struct boolGrammar : public qi::grammar<Iterator, bool, Skipper>