【问题标题】:spirit x3 cannot propagate attributes of type optional<vector>Spirit x3 无法传播 optional<vector> 类型的属性
【发布时间】:2017-03-29 09:20:32
【问题描述】:

Coliru 上的简单解析器。解析器 -(+x3::alpha) 应该能够像 Qi 一样传播 boost::optional&lt;std::string&gt; 类型的属性。但它不编译。

std::string const input = "abc";
boost::optional<std::string> attr;
if(x3::parse(boost::begin(input),boost::end(input),
    -(+x3::alpha),
    attr)) {
    std::cout<<"match!"<<std::endl;
}
else {
    std::cout<<"NOT match!"<<std::endl;
}

【问题讨论】:

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


    【解决方案1】:

    我不认为规范性声明“应该能够 [...] 像 Qi 那样”削减木材。 X3 不是 Qi 的演变,有很好的理由(例如这个)。

    一个经常出现的模式是在更复杂的传播场景中需要类型提示。丑陋的冗长方式可能是这样的:

        -(x3::rule<struct _, std::string> {} = +x3::alpha),
    

    Live On Coliru

    或者你可以使用破解 I described previously:

    namespace {
        template <typename T>
        struct as_type {
            template <typename Expr>
                auto operator[](Expr&& expr) const {
                    return x3::rule<struct _, T>{"as"} = x3::as_parser(std::forward<Expr>(expr));
                }
        };
    
        template <typename T> static const as_type<T> as = {};
    }
    

    Live On Coliru

    【讨论】:

    • 很好的解决方案!但是我还是想知道为什么x3不支持这么明显的复合属性传播?
    • 不明显。它涉及两个重要的转换。容器类型一直很棘手(-(a%b) 很有意义,因为 vector &lt;A&gt; 和 -(a*) 自然等同于 a*。
    • 在 Qi 中“足够明显”的原因可能是子解析器在内部过早地将其属性保存在显式合成类型中,导致复制属性时效率低下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2023-04-04
    • 2021-04-17
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多