2

一个简单的解析器,如Coliru上的。解析器-(+x3::alpha)应该能够boost::optional<std::string>像 Qi 那样传播类型的属性。但它不编译。

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;
}
4

1 回答 1

3

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

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

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

Live On Coliru

或者你可以使用我之前描述的黑客:

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

于 2017-03-29T12:24:30.157 回答