Example parsing error

2019-02-28 07:22发布

问题:

I'm trying to parse an example of boost spirit (2.5.2) following the example. My code is the following

#include <boost\spirit\home\qi.hpp>
#include <iostream>
#include <string>
#include <utility>

int main()
{

  // Parsing two numbers
  std::string input("1.0 2.0");
  std::pair<double, double> p;

  boost::spirit::qi::phrase_parse(
    input.begin(),
    input.end(),
    boost::spirit::qi::double_ >> boost::spirit::qi::double_ , // Parse grammar
    boost::spirit::qi::space,
    p
  );

  return 0;
}

It's almost equal to the example found here, but when I compile it with Visual studio 2010 (32 bit, debug) I obtain the following error:

error C2440: 'static_cast': unable to convert from 'const double' to 'std::pair<_Ty1,_Ty2>'

(the error can be slighty different, I've translated it from italian)

What I'm doing wrong and how can I compile successfully the example?

Thanks in advance for your replies.

回答1:

You are missing an include:

#include <boost/fusion/adapted/std_pair.hpp>

It defines the attribute assignment rules to make Fusion sequences (vector2<>) assignable to std::pair.

See the code live: liveworkspace.org

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <iostream>
#include <string>
#include <utility>

int main()
{
    // Parsing two numbers
    std::string input("1.2 3.4");
    std::pair<double, double> p;

    namespace qi = boost::spirit::qi;

    qi::phrase_parse(
            input.begin(), 
            input.end(),
            qi::double_ >> qi::double_ , // Parse grammar
            qi::space, p);

    std::cout << "Lo:     " << p.first << "\n"
              << "Behold: " << p.second << "\n";
}