C++ 模板精神X3解析器
在Boost中,很容易对解析器进行模板化,这样就可以为各种属性类型实例化解析器。我不清楚如何使用X3实现这一点。考虑一下这个删减版本: 与C++ 模板精神X3解析器,c++,boost-spirit,boost-spirit-x3,C++,Boost Spirit,Boost Spirit X3,在Boost中,很容易对解析器进行模板化,这样就可以为各种属性类型实例化解析器。我不清楚如何使用X3实现这一点。考虑一下这个删减版本: 与 这显然太天真了。如何正确地做到这一点?在X3中,动态组合解析器不会有太多困难。因此,我将您的示例写为: template <typename Attribute> auto make_roman() { using namespace boost::spirit::x3; struct numbers_ : symbols<
这显然太天真了。如何正确地做到这一点?在X3中,动态组合解析器不会有太多困难。因此,我将您的示例写为:
template <typename Attribute>
auto make_roman() {
using namespace boost::spirit::x3;
struct numbers_ : symbols<Attribute> {
numbers_() { this-> add
("I", Attribute{1}) ("II", Attribute{2}) ("III", Attribute{3}) ("IV", Attribute{4})
("V", Attribute{5}) ("VI", Attribute{6}) ("VII", Attribute{7}) ("VIII", Attribute{8})
("IX", Attribute{9}) ;
}
} numbers;
return rule<class roman, Attribute> {"roman"} =
eps [([](auto &x) { _val(x) = 0; })]
>> numbers [([](auto &x) { _val(x) += _attr(x); })];
}
看到了吗这看起来比QI中恼人的语法结构要好得多。非常感谢你!如果数字是静态的,可以避免返回类型中的类型擦除吗?@ildjarn您能详细说明一下这是什么意思吗?这个答案中没有类型擦除。规则{roman}=不是返回语句类型擦除的一部分吗?@ildjarn不。这就是你想到的精神齐
namespace parser {
// ...
}
template < typename int_t >
struct parser {
// ...
};
template <typename Attribute>
auto make_roman() {
using namespace boost::spirit::x3;
struct numbers_ : symbols<Attribute> {
numbers_() { this-> add
("I", Attribute{1}) ("II", Attribute{2}) ("III", Attribute{3}) ("IV", Attribute{4})
("V", Attribute{5}) ("VI", Attribute{6}) ("VII", Attribute{7}) ("VIII", Attribute{8})
("IX", Attribute{9}) ;
}
} numbers;
return rule<class roman, Attribute> {"roman"} =
eps [([](auto &x) { _val(x) = 0; })]
>> numbers [([](auto &x) { _val(x) += _attr(x); })];
}