将boost :: spirit :: qi :: phrase_parser()转换为std :: map错误

时间:2019-02-09 16:09:45

标签: c++ boost-spirit-qi

以下代码是将“ key = val; ..”字符串解析为std :: map,并且无法编译并显示错误:

  

错误C2146:语法错误:标识符'value_type'前缺少'>'
  错误C2039:'value_type':不是'std :: pair,std :: allocator,std :: basic_string,std :: allocator >>的成员c:\ git \ risk-engine-core_tcp \ stage \ boost- 1.66.0-barclays-1 \ include \ boost \ spirit \ home \ support \ container.hpp

它不喜欢作为容器传递的最后一个参数“ contents”(std :: map)。

提升版本为1.66

namespace qi = boost::spirit::qi;

std::map<std::string,std::string> contents;
std::string::iterator first = str.begin();
std::string::iterator last  = str.end();

const bool result = qi::phrase_parse(first,last, 
*( *(qi::char_-"=")  >> qi::lit("=") >> *(qi::char_-";") >> -qi::lit(";") ),
 ascii::space, contents); 

看着boost文档和堆栈溢出,我看不到上面的代码有任何问题。

1 个答案:

答案 0 :(得分:0)

您包括了

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

这是一个工作示例,其中包含一些改进建议:

Live On Coliru

#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <map>
#include <iomanip> // std::quoted

namespace qi = boost::spirit::qi;

int main() {
    std::string str("key = value");
    std::string::const_iterator first = str.begin();
    std::string::const_iterator last  = str.end();

    std::map<std::string, std::string> contents;
    bool const result = qi::phrase_parse(first,last, 
        *( *~qi::char_('=')  >> '=' >> *~qi::char_(';') >> -qi::lit(';') ),
         qi::ascii::space, contents); 

    if (result) {
        std::cout << "Parsed " << contents.size() << " elements\n";
        for (auto& [k,v] : contents) {
            std::cout << "\t" << std::quoted(k) << ": " << std::quoted(v) << "\n";
        }
    } else {
        std::cout << "Parse failed\n";
    }

    if (first != last)
        std::cout << "Remaining input unparsed: " << std::quoted(std::string(first, last)) << "\n";
}

打印

Parsed 1 elements
    "key": "value"