使用Boost Spirit匹配字符串

时间:2011-07-01 17:18:45

标签: c++ parsing boost boost-spirit

我正在学习Boost Spirit并简单地修改了文档中给出的示例以匹配字符串而不是双精度。但代码不编译,我得到错误,我无法调试。下面是代码和打印错误。你能帮我调试一下这个问题吗?

PS:我猜测问题在于使用phoenix :: ref作为矢量字符串,但不确定如何以及为什么。

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/config/warning_disable.hpp>

#include <iostream>
#include <string>
#include <vector>

namespace client
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    namespace phoenix = boost::phoenix;

    template <typename Iterator>

    bool parse_data(Iterator first, Iterator last, std::vector<std::string>& v)
    {
        using qi::double_;
        using qi::char_;
        using qi::phrase_parse;
        using qi::_1;
        using ascii::space;
        using phoenix::ref;
        using phoenix::push_back;

        bool r = phrase_parse(
            first,
            last,
            +(char_)[push_back(ref(v), _1)],        
            char_('/')  
        );
        if (first != last)
            return false;
        return r;
    }
}

int 
main()
{
    std::string str;

    while (getline(std::cin, str))
    {
        if (str.empty())
            break;

        std::vector<std::string> v;
        if(client::parse_data(str.begin(), str.end(), v))
        {
            std::cout << std::endl << "Parsing done" << std::endl;
            std::cout << "Numbers are " ;
            for(std::vector<std::string>::iterator i = v.begin(); i < v.end(); i++)
            {
                std::cout << *i <<" ";
            }
            std::cout << std::endl;
        }
        else
        {
            std::cout << "Parsing Failed" << std::endl;
        }
    }

    return 0;
}

这是我得到的错误:

/usr/local/include/boost_1_46_1/boost/spirit/home/phoenix/stl/container/container.hpp:492:
error: invalid conversion from ‘const char’ to ‘const char*’

/usr/local/include/boost_1_46_1/boost/spirit/home/phoenix/stl/container/container.hpp:492: 
error:   initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’

1 个答案:

答案 0 :(得分:2)

如果你把它写成

bool r = phrase_parse(
    first, last, +(char_[push_back(ref(v), _1)]), char_('/')  
);

它会起作用。但是写作

bool r = phrase_parse(
    first, last, +char_, '/', v
);

更简单(并且运行得更快)。