我正在深入研究boost :: spirit,以便解析基于ASCII的协议。我管理员使用以下规则从行中提取值:

rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_a(buffer.speed)];

我也成功地以有意义的方式连接这些规则。完美日期缺少的是:数据值是需要使用固定转换因子(通常为10的幂)转换为浮点值的整数。

我现在所做的只是在解析后应用这些缩放因子。但是,我真的会认真地将缩放因子包含在字段的规则定义中。我想象这样的事情:

rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_a(buffer.speed,100)];

有什么建议吗?

提前致谢 ·阿尔

有帮助吗?

解决方案

一种方法是使用 Boost.Phoenix 。包括这些标题:

#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp> // For static_cast_
#include <boost/spirit/include/phoenix_operator.hpp> // For multiplication

然后使用类似的东西:

using namespace boost::phoenix;
using namespace boost::phoenix::arg_names;

rule<> Speed = uint_parser<unsigned int,10,3,3>()[
    ref(buffer.speed) = static_cast_<double>(arg1) * 100
];

虽然,我发现凤凰使用起来有点棘手,通常只是写下我自己的行动

struct assign_scaled
{
    double& result;
    double scale;

    assign_with_scale(double& r, double scale) : result(r), scale(scale) {}

    void operator()(unsigned int x) const
    {
        result = static_cast<double>(x) * scale;
    }
};

并像这样使用它:

    rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_scaled(buffer.speed, 100)];

这可能更冗长,但我发现它更容易维护。

其他提示

使用Spirit.Qi,您可以使用 [ref(buffer.speed)= _1 * 100]

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top