我刚刚开始深入研究 Boost::Spirit,目前最新版本——V2.4。我的问题的本质如下:
我想解析像“1a2”或“3b4”这样的字符串。所以我使用的规则是:
(double_ >> lit('b') >> double_)
| (double_ >> lit('a') >> double_);
Run Code Online (Sandbox Code Playgroud)
规则的属性必须是“vector <double>”。我正在将其读入容器中。
完整代码:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstring>
int main(int argc, char * argv[])
{
using namespace std;
using namespace boost::spirit;
using namespace boost::spirit::qi;
using boost::phoenix::arg_names::arg1;
char const * first = "1a2";
char const * last = first + std::strlen(first);
vector<double> h;
rule<char const *, vector<double>()> or_test;
or_test %= (double_ >> lit('b') >> double_)
| (double_ >> lit('a') >> double_);
if (parse(first, last, or_test,h)) {
cout << "parse success: ";
for_each(h.begin(), h.end(), (cout << arg1 << " "));
cout << "end\n";
} else cout << "parse error\n" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我用 g++ 4.4.3 编译它。它返回“1 1 2”。虽然我期待“1 2”。
据我了解,发生这种情况是因为解析器:
我的问题是——这是正确的行为吗?如果是的话——为什么?
这是预期的行为。在回溯期间,Spirit 不会“取消”对属性的更改。因此,您应该使用该hold[]
指令显式强制解析器保留属性的副本(允许回滚任何属性更改):
or_test =
hold[double_ >> lit('b') >> double_)]
| (double_ >> lit('a') >> double_)
;
Run Code Online (Sandbox Code Playgroud)
该指令需要应用于修改属性的所有替代项(最后一个除外)。
归档时间: |
|
查看次数: |
451 次 |
最近记录: |