c++ - Boost 中的关键字列表运算符

标签 c++ boost boost-spirit-qi

我正在尝试解析一个属性顺序无关紧要的对象。

例如解析employee

employee { surname = "doe", firstname = "john", age = 30 }

应该和

一样

employee { age = 30, firstname = "john", surname = "doe"}

所以理想情况下我的规则应该是这样的(不要介意缺少正式定义)

unordered_rule %= lit("employee") >> "{" 
             >> kwd("surname")["=" > quoted_string] 
            / kwd("age")["=" > int_] 
            / kwd("firstname")["=" > quoted_string] 
            / kwd("age")["=" > int] >> "}"; 

但首先,我如何将分隔逗号合并到解析规则中?对于我的 C++ struct struct employee { std::string firstname; ... 年龄; },属性的顺序是否重要,或者即使在结构已转换为 fusion vector 之后,boost 如何知道哪个关键字对应于哪个属性?

即使在阅读了有关关键字列表运算符的文档之后,这对我来说也不是真的。

最佳答案

fusion 序列是有序的。因此,属性合成的顺序必须与字段适应 fusion 序列的顺序相匹配。

我不知道合并定界符的优雅方法(我认为有人应该为此扩展关键字列表解析器指令......随意 :))。

您可以混合使用跳过,例如(qi::space | ',')qi::lexeme[] 围绕相关项(参见 Boost spirit skipper issues )。

或者您可以使用前瞻断言的重复表达式,例如

unordered_rule %= lit("employee") >> "{" 
        >> (kwd("surname")  >> (&lit('}') | ',')) [ "=" > quoted_string ]
        / kwd("age")       >> (&lit('}') | ',')) [ "=" > int_ ]
        / kwd("firstname") >> (&lit('}') | ',')) [ "=" > quoted_string ]
        / kwd("age")       >> (&lit('}') | ',')) [ "=" > int ]
        >> "}";

(暂未测试)

关于c++ - Boost 中的关键字列表运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907603/

相关文章:

c++ - Boost SerialPort 的意外结果

c++ - 使用 Boost 编译的 Visual Studio

c++ - boost unordered_set 的意外行为

c++ - 如何使用 boost.Qi 解析此类 XML 并调用名为标签的函数?

c++ - Boost 精神解析器未编译

c++ - 演示程序错误 : '' was not declared in this scope

c++ - for 循环中的 SUM 函数,C++

c++ - 使用 gluLookAt 的 OpenGL 相机旋转

boost - 文件系统路径的 boost range 副本的编译问题

c++ - 使用boost Spirit解析带有二进制信封的文本文件