看看这个实现 Spirit 解析器的示例,当我尝试编写类似的东西时,有些东西让我很吃惊。
语法的属性模板参数(std::map<std::string, std::string>()
)和规则的签名模板参数(例如qi::rule<Iterator, std::string()> key, value
)包含括号。
namespace qi = boost::spirit::qi;
template <typename Iterator>
struct keys_and_values
: qi::grammar<Iterator, std::map<std::string, std::string>()> // <- parentheses here
{
keys_and_values()
: keys_and_values::base_type(query)
{
query = pair >> *((qi::lit(';') | '&') >> pair);
pair = key >> -('=' >> value);
key = qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9");
value = +qi::char_("a-zA-Z_0-9");
}
qi::rule<Iterator, std::map<std::string, std::string>()> query; // <- parentheses here
qi::rule<Iterator, std::pair<std::string, std::string>()> pair; // <- parentheses here
qi::rule<Iterator, std::string()> key, value; // <- parentheses here
};
我以前从未见过这个,我在编写自己的版本时无意中省略了。这导致我的解析器没有生成正确的输出运行时间(输出映射为空)。
这些括号的目的是什么?我的猜测是,这使得该规则的属性成为该类型的对象。