boost.spirit用户手册翻译(34):仿函数分析器

Functor Parser

仿函数分析器


The simplest way to write your hand coded parser that works well with the rest of the Spirit library is to simply write a functor parser.

使得你所写的代码能和Spirit其他部分合作愉快的最简单的方法就是简单地写一个仿函数分析器

A functor parser is expected to have the interface:

一个仿函数分析器应该有如下接口:

    struct functor
    {
        typedef T result_t;

        template <typename ScannerT>
        std::ptrdiff_t
        operator()(ScannerT const& scan, result_t& result) const;
    };

where typedef T result_t; is the attribute type of the parser that will be passed back to the match result (see In-depth: The Parser). If the parser does not need to return an attribute, this can simply be nil_t. The std::ptrdiff_t result is the number of matching characters matched by your parser. A negative value flags an unsucessful match.

这里typedef T result_t;是分析器的属性类,将会传回给匹配结果(见深入:分析器)。如果分析器不需要返回一个属性,这一类型可以是nil_t。std::ptrdiff_t作为结果反映了你的分析器所匹配的字符个数。复数表明匹配失败。

A conforming functor parser can transformed into a well formed Spirit parser by wrapping it in the functor_parser template:

一个符合要求的仿函数分析器可以转变为格式良好的Spirit分析器,通过把它封装在functor_parser模板中:

    functor_parser<functor> functor_p;

Example

例子

The following example puts the functor_parser into action:

下面的例子用上了functor_parser:

    struct number_parser
    {
        typedef int result_t;
        template <typename ScannerT>
        std::ptrdiff_t
        operator()(ScannerT const& scan, result_t& result) const
        {
            if (scan.at_end())
                return -1;

            char ch = *scan;
            if (ch < '0' || ch > '9')
                return -1;

            result = 0;
            std::ptrdiff_t len = 0;

            do
            {
                result = result*10 + int(ch - '0');
                ++len;
                ++scan;
            } while (!scan.at_end() && (ch = *scan, ch >= '0' && ch <= '9'));

            return len;
        }
    };

    functor_parser<number_parser> number_parser_p;

The full source code can be viewed here. This is part of the Spirit distribution.

完整代码在此查阅。这是Spirit发布包的组成部分。

To further understand the implementation, see In-depth: The Scanner for the scanner API details. We now have a parser number_parser_p that we can use just like any other Spirit parser. Example:

要进一步了解实现,可参考深入:扫描器中扫描器API的细节。我们现在有了number_parser_p,可以像使用其他Spirit分析那样使用它。例子:

    r = number_parser_p >> *(',' >> number_parser_p);




Powered by Zoundry

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值