我正在构建一个解析器来执行用户可以在命令行上输入的命令。命令的第一部分是它所属的模块,第二部分是模块的调用函数。
附加到第一个解析器的是一个语义操作(使用boost :: phoenix :: ref()),它应该将模块的名称存储在变量 m_moduleName 中。附加到第二个解析器的是另一个语义操作,它使用前一个变量作为参数调用函数printParameters。
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/home/qi.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
void printParameters(const std::string & module, const std::string & command)
{
std::cout << "Module name during parse: " << module << std::endl;
std::cout << "Command name during parse: " << command << std::endl;
}
template <typename Iterator>
struct myCommandParser : public qi::grammar<Iterator>
{
myCommandParser() : myCommandParser::base_type(start)
{
start = qi::as_string[+(~qi::char_(' '))][phoenix::ref(m_moduleName) = qi::_1]
>> qi::as_string[+(~qi::char_('\n'))][boost::bind(&printParameters, m_moduleName, ::_1)];
};
qi::rule<Iterator> start;
std::string m_moduleName;
};
int main()
{
myCommandParser<std::string::const_iterator> commandGrammar;
commandGrammar.m_moduleName = std::string("initial_default");
std::cout << "Module name before parsing: " << commandGrammar.m_moduleName << std::endl;
std::string str("mod01 cmd02\n");
std::string::const_iterator first = str.begin();
std::string::const_iterator last = str.end();
qi::parse(first, last, commandGrammar);
std::cout << "Module name after parsing: " << commandGrammar.m_moduleName << std::endl;
}
预期结果: 在第一个语义操作期间,m_moduleName的值应设置为 mod01 ,应在printParameters函数期间打印。
实际结果(节目输出):
Module name before parsing: initial_default
Module name during parse:
Command name during parse: cmd02
Module name after parsing: mod01
在构造这个最小的例子时,我注意到在执行解析函数期间m_moduleName的值是空,尽管它已被设置为&#34; initial_default&#34;预先。
有人可以解释一下究竟发生了什么吗?
为什么值为空而不是 mod01 ?