【问题标题】:Boost::Spirit : Basic "logical and" expression parsingBoost::Spirit:基本的“逻辑与”表达式解析
【发布时间】:2016-06-12 01:20:34
【问题描述】:

我正在尝试学习 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"

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

【问题讨论】:

  • 前段时间我问了一个类似的问题。这应该对你有帮助:stackoverflow.com/questions/14548592/…
  • 非常感谢,确实如此!我将船长添加为模板参数,它可以工作。我想没有它,我的语法不知何故默认为不正确的空格跳过。

标签: c++ parsing boost boolean-logic


【解决方案1】:

通过添加skipper作为模板参数解决,如@Richard Hodges之前的问题所示:

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

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 2014-09-13
    • 2020-11-03
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    相关资源
    最近更新 更多