2

我需要解析一个键值对,其中键本身是一个固定字符串 lke 'cmd' 在示例中。不幸的是 qi::lit 没有综合属性并且 qi::char_ 解析没有固定的字符串。以下代码无法编译。执行后我需要那个 result.name == cmd 。

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType
{
  std::string name;
  int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type> rule = qi::lit("cmd") >> "=" >> qi::int_;

    for (std::string const s : {"cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}
4

1 回答 1

1

qi::lit不公开属性。qi::string做:

    rule = qi::string("cmd") >> "=" >> qi::int_;

住在科利鲁

#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
#include <string>

namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;

struct CommandRuleType {
    std::string name;
    int arg;
};

BOOST_FUSION_ADAPT_STRUCT(CommandRuleType, name, arg)

int main() {
    qi::rule<std::string::const_iterator, CommandRuleType(), qi::space_type>
        rule = qi::string("cmd") >> "=" >> qi::int_;

    for (std::string const s : { "cmd = 1" }) {
        std::cout << std::quoted(s) << " -> ";
        CommandRuleType result;
        if (qi::phrase_parse(s.begin(), s.end(), rule, qi::space, result)) {
            std::cout << "result: " << result.name << "=" << result.arg << "\n";
        } else {
            std::cout << "parse failed\n";
        }
    }
}

印刷

"cmd = 1" -> result: cmd=1
于 2020-06-15T16:09:08.870 回答