【问题标题】:qi::rule with inherited attribute as inherited attributeqi::rule 继承属性作为继承属性
【发布时间】:2017-03-06 20:27:33
【问题描述】:

假设我们有一个规则1

qi::rule<std::string::iterator, int()> rule1 = qi::int_[qi::_val=qi::_1];

而且我们决定只获得一个 int 作为属性是不够的,我们还想获得原始数据(boost::iterator_range)。我们可能有很多与 rule1 相同类型的规则。所以最好有一个通用的解决方案。因此我们可以定义另一个规则2。

qi::rule<
    std::string::iterator,
    std::pair<int, boost::iterator_range<std::string::iterator>>(
        qi::rule<std::string::iterator, int()>&
    )
> rule2 = qi::raw[
    qi::lazy(qi::_r1)[at_c<0>(qi::_val)=qi::_1]
][at_c<1>(qi::_val)=qi::_1];

rule2 与测试代码配合良好。

std::pair<int, boost::iterator_range<std::string::iterator>> result;
auto itBegin=boost::begin(str);
auto itEnd=boost::end(str);
if (qi::parse(itBegin, itEnd, rule2(phx::ref(rule1)), result)) {
    std::cout<<"MATCH! result = "<<result.first<<", "<<std::string(boost::begin(result.second), boost::end(result.second))<<std::endl;
} else {
    std::cout<<"NOT MATCH!"<<std::endl;
}

但是如果 rule1 采用一个继承的属性,比如说一个布尔值。

qi::rule<std::string::iterator, int(bool)> rule1 = qi::int_[
    if_(qi::_r1)[qi::_val=qi::_1]
    .else_[qi::_val=-1]
;

出于测试目的,我们简单地将 true 从 rule2 传递给 rule1。

qi::rule<
    std::string::iterator,
    std::pair<int, boost::iterator_range<std::string::iterator>>(
        qi::rule<std::string::iterator, int(bool)>&
    )
> rule2 = qi::raw[
    qi::lazy(qi::_r1)(true)[at_c<0>(qi::_val)=qi::_1]
][at_c<1>(qi::_val)=qi::_1];

但是编译器会报error_invalid_e test xpression错误。这有什么问题吗?谢谢。

【问题讨论】:

    标签: c++ boost boost-spirit boost-spirit-qi boost-phoenix


    【解决方案1】:

    phx::bind 实际上解决了这个问题。

    qi::rule<
        std::string::iterator,
        std::pair<int, boost::iterator_range<std::string::iterator>>(
            qi::rule<std::string::iterator, int(bool)>&
        )
    > rule2 = qi::raw[
        qi::lazy(phx::bind(qi::_r1,true))[at_c<0>(qi::_val)=qi::_1]
    ][at_c<1>(qi::_val)=qi::_1];
    

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2012-05-08
      • 2012-08-15
      • 2010-10-05
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      相关资源
      最近更新 更多