【发布时间】: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