c++ - qi::rule 以继承属性作为继承属性

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

假设我们有一条规则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采用继承属性,比如bool。

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错误。这其中有什么问题吗?谢谢。

最佳答案

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];

关于c++ - qi::rule 以继承属性作为继承属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42634929/

相关文章:

c++ - boost::bind 与空函数指针

c++ - 如何通过 boost spirit 提取 std::string 对象

c++ - alloca() 的这种使用有效吗?

c++ - 同时读取和写入文件?

c++ - boost 字符串拆分以消除单词中的空格

c++ - 编译 boost::math 的性能测试应用程序

c++ - 使用 GCC 而不是 MSVC 构建时使用模板编译错误

c++ - 对全局数组的 undefined reference

c++ - 带有调试输出的 X3 解析器段错误 (BOOST_SPIRIT_X3_DEBUG)

c++ - boost::spirit::qi 排列解析器和合成属性