2

这是一个代码示例。

// file temp.cpp

#include <iostream>

#include <vector>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

struct parser : qi::grammar<std::string::const_iterator, std::vector<double> >
{
    parser() : parser::base_type( vector )
    {
        vector  = +qi::double_;
    }

    qi::rule<std::string::const_iterator, std::vector<double> > vector;
};

int main()
{
    std::string const x( "1 2 3 4" );
    std::string::const_iterator b = x.begin();
    std::string::const_iterator e = x.end();
    parser p;
    bool const r = qi::phrase_parse( b, e, p, qi::space );
    // bool const r = qi::phrase_parse( b, e, +qi::double_, qi::space ); // this this it PASSES
    std::cerr << ( (b == e && r) ? "PASSED" : "FAILED" ) << std::endl;
}

我想std::string xparser p.

从 的定义如下 struct parser,行

qi::phrase_parse( b, e, p, qi::space ); // PASSES

qi::phrase_parse( b, e, +qi::double_, qi::space ); // FAILS

应该是等价的。但是,第一个解析失败,第二个解析通过。

我在定义上做错了struct parser什么?

4

1 回答 1

2

您应该“告知”有关跳过空格的语法 - 模板中的另一个参数。

#include <iostream> 

#include <vector> 
#include <boost/spirit/include/qi.hpp> 

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;

struct parser
  : qi::grammar<std::string::const_iterator, std::vector<double>(), ascii::space_type> 
{ 
  parser() : parser::base_type( vector ) 
  { 
    vector  %= +(qi::double_); 
  } 

  qi::rule<std::string::const_iterator, std::vector<double>(), ascii::space_type> vector;
}; 

int main() 
{ 
  std::string const x( "1 2 3 4" ); 
  std::string::const_iterator b = x.begin(); 
  std::string::const_iterator e = x.end(); 
  parser p; 
  bool const r = qi::phrase_parse( b, e, p, ascii::space ); 
  //bool const r = qi::phrase_parse( b, e, +qi::double_, qi::space );
  std::cout << ( (b == e && r) ? "PASSED" : "FAILED" ) << std::endl; 
} 

我也做了一些小的更正,例如你应该在参数中添加括号,它告诉属性类型:std::vector<double>()

于 2012-02-24T12:31:34.063 回答