8

我已经成功地使用boost::spirit::qito 来解析由内置解析器(例如,等)组成的byte_little_word。但是,我现在需要解析不完全属于这些类别之一的数据。比如我想把一个16.16的定点二进制数转换成double;例如,little_word << little_16p16将解析 auint16_t后跟 a double(从定点数解析)。

我首先考虑了语义动作,但(我认为......)它们不合适,因为它们不会更改与解析器关联的属性的类型。我也无法弄清楚如何使员工结构解析示例适应这种情况,因为它依赖于boost::fusion. 这种方法在这里行不通,因为我显然无法uint32_tdouble不引起重大问题的情况下定义隐式转换。

我的倾向是我需要添加非终端来包装内置的二进制原始解析器或从头开始编写终端解析器。即使查看了 的来源qi_binary.hpp,我也不知道该怎么做。任何人都可以提供一些示例代码和/或指导我参考相关参考资料以开始使用吗?

4

1 回答 1

7
    template < typename Iterator >
    struct parser : boost::spirit::qi::grammar < Iterator, double(), boost::spirit::ascii::space_type >
    {
        struct cast_impl
        {
            template < typename A >
            struct result { typedef double type; };

            double operator()(boost::fusion::vector < boost::uint16_t, boost::uint16_t > arg) const
            {
                // cast here
                return 0;
            }
        };

        parser() : parser::base_type(main)
        {
            pair = boost::spirit::qi::little_word >> '.' >> boost::spirit::qi::little_word;
            main = pair[boost::spirit::qi::_val = cast(boost::spirit::qi::_1)];
        }

        boost::spirit::qi::rule < Iterator, boost::fusion::vector < boost::uint16_t, boost::uint16_t > (), boost::spirit::ascii::space_type > pair;
        boost::spirit::qi::rule < Iterator, double(), boost::spirit::ascii::space_type > main;

        boost::phoenix::function<cast_impl> cast;
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
        typedef std::string container;

        container data_ = "\x01\x02.\x01\x02";

        container::iterator iterator_ = data_.begin();

        double value_;

        bool result_ =
            boost::spirit::qi::phrase_parse(iterator_, data_.end(),
            parser < container::iterator > (),
            boost::spirit::ascii::space,
            value_);

        return 0;
    }
于 2012-03-15T12:50:03.770 回答