如何通过boost spirit提取std :: string对象

时间:2014-02-07 08:39:10

标签: c++ boost boost-spirit boost-spirit-qi

我有以下代码:

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/spirit/include/qi.hpp>

#include <iostream>
#include <string>

struct function
{
  std::string ret_type;
  std::string name;
};

BOOST_FUSION_ADAPT_STRUCT(
  ::function,
  (std::string, ret_type)
  (std::string, name)
)

template <typename Iterator>
struct function_parser : boost::spirit::qi::grammar<Iterator, function(), boost::spirit::qi::ascii::space_type>
{
  function_parser() : function_parser::base_type(start)
  {
    using boost::spirit::qi::ascii::char_;
    using boost::spirit::qi::int_;

    start %= +char_ >> +char_;
  }

  boost::spirit::qi::rule<Iterator, function(), boost::spirit::qi::ascii::space_type> start;
};

int main()
{
  std::string input_data("void foo");

  function fn;
  auto itr = input_data.begin();
  auto end = input_data.end();
  function_parser<decltype(itr)> g;
  bool res = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::ascii::space, fn);
  if (res && itr == end)
  {
    std::cout << boost::fusion::tuple_open('[');
    std::cout << boost::fusion::tuple_close(']');
    std::cout << boost::fusion::tuple_delimiter(", ");

    std::cout << "Parsing succeeded\n";
    std::cout << "got: " << boost::fusion::as_vector(fn) << std::endl;
  }
  else
  {
    std::cout << "Parsing failed \n";
  }
}

输出

  

解析失败

我做错了什么?我该如何解决?

1 个答案:

答案 0 :(得分:1)

+char_

吃掉所有输入!现在,下一个

+char_

要求至少一个字符,不存在(第一个kleen加上它),所以解析失败。

我建议改为:

    using namespace boost::spirit::qi;

    start = lexeme[+graph] >> lexeme[+graph];

文档应该能够告诉你这是做什么的(我希望。没时间详细说明)