2014-02-08 63 views
1

我有以下代碼:提振精神,提升和任何引用字符串 - 編譯時錯誤

#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

再次,爲什麼將你想使問題複雜化使其緩慢通過boost::any

無論如何,+char_公開std::vector<char>,顯然屬性兼容性規則不想決定如何轉換它。

讓它明確與as_stringLive 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"; 
     } 
    } 
}