使用多个with指令时,如何声明Boost.Spirit X3的context类型?
如何为Boost.Spirit X3中多个
with指令声明对应的context类型 我了解到可以通过嵌套with指令同时传递position_cache和error_handler这类信息,初始化解析器的配置方式如下:
with<tag1>(data1) [ with<tag2>(data2)[p] ]
但不确定同时使用两个tag时,该如何配置解析器的context类型。官方示例中只有单个with指令的context声明:
typedef x3::context< error_handler_tag , std::reference_wrapper<error_handler_type> , phrase_context_type> context_type;
想知道针对支持两个不同tag的解析器,该如何声明对应的context类型?
解答
Boost.Spirit X3的x3::context是嵌套式的模板结构,每个context实例都包含当前tag、对应的数据类型,以及父context类型。要支持多个with指令的嵌套,只需要按照相同的嵌套顺序来构建context类型即可。
比如,假设你需要同时传递position_cache_tag(对应std::reference_wrapper<position_cache>)和error_handler_tag(对应std::reference_wrapper<error_handler_type>),且基础context是phrase_context_type,那么对应的context_type声明应该是:
typedef x3::context< position_cache_tag, std::reference_wrapper<position_cache>, // 内层嵌套error_handler的context,父context为phrase_context_type x3::context< error_handler_tag, std::reference_wrapper<error_handler_type>, phrase_context_type > > context_type;
这个结构和你嵌套with指令的逻辑完全对应:
- 最底层是基础的
phrase_context_type - 外层包裹
error_handler_tag对应的context(对应内层的with<tag2>(data2)) - 最外层包裹
position_cache_tag对应的context(对应外层的with<tag1>(data1))
这样声明后,解析器就能在context中同时获取到两个tag对应的数据了。
内容的提问来源于stack exchange,提问作者Alfred Li
相关产品推荐
相关产品推荐

