提升精神,提升任何和引用的字符串 - 编译时错误

时间:2014-02-08 14:34:01

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

我有以下代码:

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

#include <iostream>
#include <string>

template <typename Iterator>
struct parser : boost::spirit::qi::grammar<Iterator, boost::any(), boost::spirit::qi::ascii::space_type>
{
  parser() : parser::base_type(start)
  {
    start %= boost::spirit::qi::int_ | boost::spirit::qi::lexeme['"' >> +(boost::spirit::qi::char_ - '"') >> '"']; // example: 0 or "str"
  }

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

int main()
{
  const std::string input_data("\"str\"");

  boost::any var = 0;
  auto itr = input_data.begin();
  auto end = input_data.end();
  parser<decltype(itr)> g;
  bool res = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::ascii::space, var);
  if (res && itr == end)
  {
    std::cout << "Parsing succeeded \n";
    try
    {
      std::cout << boost::any_cast<std::string>(var) << '\n';
    }
    catch (const boost::bad_any_cast& ex)
    {
      std::cerr << ex.what() << '\n';
    }
  }
  else
  {
    std::cout << "Parsing failed \n";
  }
}

在我添加

之前编译好
boost::spirit::qi::lexeme['"' >> +(boost::spirit::qi::char_ - '"') >> '"']

由于字符数量限制,我无法在此处和pastie.org上发布错误。

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

1 个答案:

答案 0 :(得分:1)

再次,为什么您想要使问题复杂化使用boost::any使其变慢?

无论如何,+char_公开std::vector<char>,显然属性兼容性规则不想决定将其转换为什么。

使用as_string Live On Coliru

明确说明
#include <boost/any.hpp>
#include <boost/spirit/include/qi.hpp>

#include <iostream>
#include <string>

template <typename Iterator>
struct parser : boost::spirit::qi::grammar<Iterator, boost::any(), boost::spirit::qi::ascii::space_type>
{
    parser() : parser::base_type(start)
    {
        using namespace boost::spirit::qi;
        start %= int_ | as_string [ lexeme['"' >> +(char_ - '"') >> '"'] ]; // example: 0 or "str"
    }

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

int main()
{
//  const std::string input_data("\"str\"");
    const std::string input_data("123");
    for (std::string const& input_data : { "\"str\"", "123" })
    {
        boost::any var = boost::none;
        auto itr = input_data.begin();
        auto end = input_data.end();
        parser<decltype(itr)> g;
        bool res = boost::spirit::qi::phrase_parse(itr, end, g, boost::spirit::ascii::space, var);
        if (res && itr == end)
        {
            std::cout << "Parsing succeeded \n";
            try { std::cout << boost::any_cast<int>        (var) << '\n'; } catch (const boost::bad_any_cast& ex) { std::cerr << ex.what() << '\n'; }
            try { std::cout << boost::any_cast<std::string>(var) << '\n'; } catch (const boost::bad_any_cast& ex) { std::cerr << ex.what() << '\n'; }
        }
        else
        {
            std::cout << "Parsing failed \n";
        }
    }
}