使用Boost Spirit将默认值分配给变量 [英] Assign default value to variable using boost spirit

查看:60
本文介绍了使用Boost Spirit将默认值分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要解析以下字符串:

Suppose I have the following string to parse:

"1.2、2.0、3.9"

"1.2, 2.0, 3.9"

,当我为其应用以下解析器时:

and when I apply the following parser for it:

struct DataStruct
{
    double n1, n2, n3;
};

BOOST_FUSION_ADAPT_STRUCT(DataStruct, (double, n1)(double, n2)(double, n3))

qi::rule<std::string::iterator, DataStruct()> data_ =
                                                      qi::double_ >> ','
                                                   >> qi::double_ >> ','
                                                   >> qi::double_;

auto str = "1.2, 2.0, 3.9";
auto it - str.begin();
if (qi::parse(it, str.end(), data_, res))
{
    std::cout << "parse completed" << std::endl;
}

一切正常,但是当我假设我的字符串不是某个双精度数时,我可以得到"null"(即"1.2,null,3.9"),我想在DataStruct中将0值分配给适当的double值.有什么办法吗?

everything is ok, but when I suppose that instead of some double in my string I can get "null" (i.e. "1.2, null, 3.9") I want to assign 0 value to appropriate double value in DataStruct. Is any way to do this ?

推荐答案

通常的技巧是将qi::attr用作替代方案:

The usual trick is to use an alternative with qi::attr:

rule_def = parser_expression | qi::attr(default_value);

在您的情况下,也许:

reader_ = qi::double_ | qi::lit("null") >> qi::attr(0);

演示

在Coliru上直播

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
struct DataStruct { double n1, n2, n3; };

BOOST_FUSION_ADAPT_STRUCT(DataStruct, n1, n2, n3)

namespace qi = boost::spirit::qi;

int main() {
    using Iterator = typename std::string::const_iterator;

    qi::rule<Iterator, double()> reader_   = qi::double_ | qi::lit("null") >> qi::attr(0);
    qi::rule<Iterator, DataStruct()> data_ = reader_ >> ',' >> reader_ >> ',' >> reader_;

    DataStruct res;
    auto const str = std::string("1.2,null,3.9");
    Iterator start = str.begin(), end = str.end();

    if (qi::parse(start, end, data_ >> qi::eoi, res)) {
        std::cout << "parsed: " << boost::fusion::as_vector(res) << "\n";
    }
    else {
        std::cout << "parse failed\n";
    }
}

打印

parsed: (1.2 0 3.9)

注意评论的更改(不要使用名称空间,请检查eoi).

Note the review changes (don't using namespace, check for eoi).

这篇关于使用Boost Spirit将默认值分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆